When do I need to cache variables in local scope in (cross-browser) JavaScript?

Basically, I thought that the fewer variables I declare, the better. So when I looked at the notes for the presentation in Julien Lekomt’s conversation and found that he was declaring local variables in order to reduce overhead.

var arr = ...;
var globalVar = 0;
(function () {
    var i;
    for (i = 0; i < arr.length; i++) {
        localVar++;
    }
})();

/* vs */

var arr = ...;
var globalVar = 0;
(function () {
    var i, l , localVar;
    l = arr.length;
    localVar = globalVar;
    for (i = 0; i < l; i++) {
        localVar++;
    }
    globalVar = localVar;
})();

/* (faster on all A-grade browsers) */

Edit : when developing a website / website based on JavaScript to work in all modern desktop and mobile browsers, are there cases when I always prefer to cache variables in the local area due to the cost of the search? (for example, when accessing more than once to an object assigned myArray[100][20][40][90]or changing several properties of an object that overlays many levels of the current area, cycles of thousands?)

, , ?

+4
1

T.J. , . :

  • "" .
  • "" "".
  • !

, ( , ) "myArray", myArray[100][20][40][90], , , !

0

All Articles