Last active
August 29, 2015 13:57
-
-
Save GZShi/9385109 to your computer and use it in GitHub Desktop.
不服跑分。for-loop VS. Array.map VS. Array.every
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function benchmark (times) { | |
var index = Math.floor(Math.random()*times); | |
function fn (elem, i, array) { | |
array[i] = Math.sqrt(array[i]); | |
return true; | |
} | |
var a = []; | |
var b = []; | |
var c = []; | |
var d = []; | |
console.time('init'); | |
for(var i = 0; i < times; ++i) { | |
a.push(i); | |
b.push(i); | |
c.push(i); | |
d.push(i); | |
} | |
console.timeEnd('init'); | |
console.time('for'); | |
for(var i = 0, len = a.length; i < len; ++i) { | |
a[i] = Math.sqrt(a[i]); | |
} | |
console.timeEnd('for'); | |
console.log(' ' + a[index]); | |
console.time('for fn'); | |
for(var i = 0, len = b.length; i < len; ++i) { | |
fn(b[i], i, b); | |
} | |
console.timeEnd('for fn'); | |
console.log(' ' + b[index]); | |
console.time('map'); | |
c.map(fn); | |
console.timeEnd('map'); | |
console.log(' ' + c[index]); | |
console.time('every'); | |
d.every(fn); | |
console.timeEnd('every'); | |
console.log(' ' + d[index]); | |
} | |
benchmark(0xFFFFF); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment