简体   繁体   中英

Performances of running code in Global space vs. in a Function in Javascript

If I run in the console of Chrome this code:

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 these results:

object:      820.718ms
loop while: 1542.202ms
loop for:   1775.736ms

However if I run it in a function like:

!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 trigger some sort of VM magic to optimize the code and run it almost 4x faster. And if I run the arrayOfRandoms function by itself a couple of times the result become event better:

object:     550.601ms (2x)
loop while: 175.694ms (8x)
loop for:   187.462ms (9x)

Is the browser optimizing code written inside a functions better than the code written in the global scope? (or I messed up the console.time :) ?

Global namespace is an object and to get value from there JS compiler does something like this:

globals.findValueByKey("arr");

each time it needs to access global arr .

While to get value of local variable is exactly "get element of array by known index":

const ARR_VARIABLE_CELL_IDX = 2; // const computed at compile time.

locals[ARR_VARIABLE_CELL_IDX];

and access by index is faster as you can imagine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM