console.time("Test");
for(var i=0; i
In a web browser(Chrome), declaring the variable i outside of any function scope makes it global and therefore binds to window object. As a result, running this code in a web browser requires repeatedly resolving the property within the heavily populated window namespace in each iteration of the for loop.
In Node.js however, declaring any variable outside of any function’s scope binds it only to the module scope (not the window object) which therefore makes it much easier and faster to resolve.
We will get more or less same execution speed when we wrap the above code in function.
It's far from being as dramatic now, but I did get 2x boost from 5.417ms down to 2ms on your test. I had near absolute same values on Node and Chrome when I used a larger loop and a function wrap.
(function(){
console.time("Test");
for(var i=0; i <10000000000; i +=1 ){
// loop around
}
console.timeEnd("Test");
}).call(this);
Its Due To SCOPE in JavaScript
In Browser console code without scope : Takes lots of time : Test: 1154.19ms
below code will be kept in heavily populated window object which will take time to resolve;
console.time("Test");
for(var i=0; i <2500000; i +=1 ){
// loop around
}
console.timeEnd("Test");
In Browser console code with scope : Takes less time Test: 3.06ms
below code will be kept inside JavaScript scope and scope will be almost empty so less time
function rocket(){
console.time("Test");
for(var i=0; i <2500000; i +=1 ){
// loop around
}
console.timeEnd("Test");
}
rocket()
In Nodejs REPL : code without scope : Test: 14ms
Unexpected But nodejs most outer scope contains some bunch of variables
console.time("Test");
for(var i=0; i <2500000; i +=1 ){
// loop around
}
console.timeEnd("Test");
In Nodejs REPL : code with scope : Test: 2ms
below code will be kept inside JavaScript scope and scope will be almost empty so less time
function rocket(){
console.time("Test");
for(var i=0; i <2500000; i +=1 ){
// loop around
}
console.timeEnd("Test");
}
rocket()
Conclusion : Its all due to SCOPE and SCOPING in JavaScript is done by functions
Means if you create new function ,the place inside curly brackets {} is called as SCOPE and it will be empty initially, and if you create variable in this scope it will take no time to execute