If I run this code in the Chrome console:
console.time('object');
var arr = Object.keys([].concat(Array(1000001).join().split(''))).map(Math.random)
console.timeEnd('object');
console.time('loop while');
var arr = [];
var i = 1000000;
while(i--){
arr.push(Math.random());
}
console.timeEnd('loop while');
console.time('loop for');
var arr = [];
for(var i = 0; i < 1000000; i++){
arr.push(Math.random());
}
console.timeEnd('loop for');
I get the following results:
object: 820.718ms
loop while: 1542.202ms
loop for: 1775.736ms
However, if I ran it in a function such as:
!function arrayOfRandoms() {
console.time('object');
var arr = Object.keys([].concat(Array(1000001).join().split(''))).map(Math.random)
console.timeEnd('object');
console.time('loop while');
var arr = [];
var i = 1000000;
while(i--){
arr.push(Math.random());
}
console.timeEnd('loop while');
console.time('loop for');
var arr = [];
for(var i = 0; i < 1000000; i++){
arr.push(Math.random());
}
console.timeEnd('loop for');
}()
I get completely different results:
object: 846.752ms (about the same)
loop while: 418.416ms (about 4x faster)
loop for: 398.790ms (about 4x faster)
It seems that the function launches some kind of magic of the virtual machine to optimize the code and runs it almost 4 times faster. And if I run the function arrayOfRandomson its own, the result will be much better:
object: 550.601ms (2x)
loop while: 175.694ms (8x)
loop for: 187.462ms (9x)
Is browser optimization code written inside functions better than code written in a global area? (or did I mess up console.time :)?
source
share