Scenario 1:
console.time("loop");
for (var i = 0; i < 1000000; i += 1){
// Do nothing
}
console.timeEnd("loop");
Ran in Chrome's console, this will return apx 450ms or so.
Scenario 2:
function test() {
console.time("loop");
for (var i = 0; i < 1000000; i += 1){
// Do nothing
}
console.timeEnd("loop");
}
test();
Run this code is Chrome's console and it's usually < 1ms. I get this function example from an article on Node interview questions. I understand that the loop outside of the function will have i
resolve to a window object whereas the same loop inside the function scopes i
locally - hence the performance increase.
My question is, would it be good practice to put your loops into functions where possible? That kind of performance increase is tempting, but it seems weird to always have loops in functions as I've not seen code looking like that.