Curious JavaScript performance dependent on variable scope

When testing the performance of one JavaScript project, I noticed a very peculiar behavior - the performance of accessing JavaScript memberships seems to depend heavily on the volume in which they are located. I wrote several performance tests, and the results were different: several orders of magnitude .

I tested the 64-bit version of Windows 10 using these browsers:

Here are the most relevant tests that I have performed and their respective results:

// Code running on global scope, accessing a variable on global scope
// Google Chrome:   63000 ms.
// Mozilla Firefox: 57000 ms.
// Microsoft Edge:  21000 ms.
var begin = performance.now();
var i;
for(i = 0; i < 100000000; i++) { }
var end = performance.now();
console.log(end - begin + " ms.");


// Code running on local scope, accessing a variable on global scope
// Google Chrome:   61500 ms.
// Mozilla Firefox: 47500 ms.
// Microsoft Edge:  22000 ms.
var begin = performance.now();
var i;
(function() {
    for(i = 0; i < 100000000; i++) { }
})();
var end = performance.now();
console.log(end - begin + " ms.");

// Code running on local scope, accessing a variable on local scope
// Google Chrome:   50 ms.
// Mozilla Firefox: 28 ms.
// Microsoft Edge:  245 ms.
var begin = performance.now();
(function() {
    var i;
    for(i = 0; i < 100000000; i++) { }
})();
var end = performance.now();
console.log(end - begin + " ms.");

The difference between the code executed in local and global areas was within the margin of error, although Firefox seems to have achieved a fairly stable performance increase of 20% in the local area.

The biggest surprise was access to the variable in the local area, it was 1200 to 1600 times faster in Chrome and Firefox and 90 times faster on Edge.

Why is this so on three different browsers / javascript engines?

+4
source share
3 answers

, JavaScript V8 ( , Chrome), Node.js --print_opt_code node. , test.js, :

node --print_opt_code test.js

V8 i RAX . , , . ( , .)

 84  33c0           xorl rax,rax                 ; i = 0
 86  3d00e1f505     cmp rax, 0x5f5e100           ; compare i with 100000000
 91  0f8d12000000   jge 115                      ; exit loop if i >= 100000000
 97  493ba548080000 REX.W cmpq rsp, [r13+0x848]  ; check for bailout?
104  0f8246000000   jc 180                       ; bailout if necessary
110  83c001         addl rax, 0x1                ; i++
113  ebe3           jmp 86                       ; back to top of loop
115  ...

, 0x5f5e100 100000000, .

, . - JavaScript; , , 97 104, , .

JavaScript, . , Node , . , - , , :

for(global.i = 0; global.i < 100000000; global.i++) { }

, Node ; Node, .

+4

, , @Freddie. - , . , JIT- , , -, .

+3

1 - http://www.webreference.com/programming/javascript/jkm3/index.html

, . JavaScript, , . , , alert(), window.alert(). , .

+1

All Articles