Ad

Array For-loop: Temp Save The Array[i] Or Keep Calling Array[i] ? Which Is Better/faster?

- 1 answer

I'm trying to find out if I should temporally copy an array item while I work with it inside a for-loop. Is there any performance difference ? Other than making the code more readable. (JavaScript)

var max = someArray.length;
for (var i = 0; i < max; i++) {
   // Here I will use someArray[i] quite often. Like this:
   if (someArray[i].position.y > blabla) {
       //...
   }
}

OR:

var max = someArray.length;
for (var i = 0; i < max; i++) {
   var tmp = someArray[i]; // <---- CHANGE
   // Here I will use tmp quite often. Like this:
   if (tmp.position.y > blabla) {
       //...
   }
}
Ad

Answer

Caveat: Worry about performance when you have a specific performance problem to worry about. Until then, write whatever seems clearest and least error prone to you and your team. 99.999999% of the time, the specific performance of a given loop just won't matter in real world terms.

With that said:

With modern JavaScript, I'd probably use a for-of loop (ES2015+) instead:

for (const entry of someArray) {
    if (entry.position.y > blabla) {
        // ...
    }
}

In theory, that uses an iterator behind the scenes, which involves function calls; in practice, it's likely that if you're dealing with an actual array and that array uses the standard iterator, the JavaScript engine will be able to optimize the loop if the loop is a hot spot (and if it isn't, it's not worth worrying about).

Re your two alternatives, if i and someArray don't change in the loop and someArray is just a normal array, the JavaScript engine is likely to be able to optimize it into something like your second loop. As a matter of style, before for-of I always used a local within the loop rather than retyping someArray[i] each time, but that's just because it's easier to type tmp (or some more meaningful name) than someArray[i].

If there's a reason to believe that a specific loop is being slow (so for some reason, it's not getting optimized), then I might go with something like your second example:

for (let i = 0, max = someArray.length; i < max; i++) {
   const tmp = someArray[i];
   if (tmp.position.y > blabla) {
       //...
   }
}

But again, this is mostly a matter of style until/unless you have a specific performance problem you're diagnosing and fixing.

Ad
source: stackoverflow.com
Ad