|
|
|
|
|
by webuiarchitect
5848 days ago
|
|
We are talking about performance optimization here; which means 'what will work faster' over conventional approaches. Every time the scripting engine doesn't find a variable in the local scope, it starts searching for it upwards until it reaches global namespace. And this, my friend, costs CPU cycles. Now consider this out-of-scope variable being used in a loop. Closure is a power JavaScript has given us to use it wisely; and not to misuse. |
|
For example, if you ran the code below in FireBug you'll get the same results (minor variance aside).
function foo() { var a = 0; for (var i=0, j=a; i<10000000; i++) { var x = j+i; } }
function bar() { var a = 0; for (var i=0; i<10000000; i++) { var x = a+i; } }
(function() { var start = new Date().getTime(), end; foo(); end = new Date().getTime(); console.log(end-start); })();
(function() { var start = new Date().getTime(), end; bar(); end = new Date().getTime(); console.log(end-start); })();