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
ifrom 0 to several million. The V8 engine's JIT compiler will optimize parts like this and may not even run the loop at all if it can get the same result. As you can see, this will depend on the environment the JS is run in. This is a relevant JS talk on performance and benchmarking: youtube.com/watch?v=65-RbBwZQdU