DEV Community

Discussion on: Why you should stop declaring variables inside a for loop (especially in JavaScript)

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

For loop-internal variables, this shouldn't actually save any memory on average. I mean, if the garbage collector is really stupid (most aren't), it might, but not much unless you've got a lot of variables inside the loop that are only ever primitives. OTOH, it should save some time, because you don't have to allocate memory on every loop iteration.

For the actual counter variable though, it's not as clear cut. In terms of runtime and memory usage, there should be near zero difference in the totals between these two code samples:

let i
for (i = 0; i < 10; i++) {
    // do something
}
for (let i = 0; i < 10; i++) {
    // do something
}

The reason is simple: Internally, that first part of the loop expression (the i = 0 part) runs exactly once. So moving the counter declaration outside of the loop expressions just changes the scope, nothing else. Somewhat counter-intuitively, this may even make the loop run slower if you are accessing the counter inside the loop a lot (I know of no JS engine that actually has this issue, but a trivial naive implementation of the JS scoping rules would cause it to run slower).

If, however, you can safely reuse the counter variable across multiple loops, then you might save some time this way, but you won't really save much space long-term. The important part there though is 'safely', you usually have to at least scope the declarations to the containing function so that you don't end up manipulating other loops states accidentally, so you're not likely to save much time either unless you're doing a lot of looping.

Collapse
 
jamesthomson profile image
James Thomson

Internally, that first part of the loop expression (the i = 0 part) runs exactly once. So moving the counter declaration outside of the loop expressions just changes the scope, nothing else.

Came here to say this. Placing the let within the for expression doesn't mean it's being created every loop. It's only created once, it's more concise, and it's scoped to the for loops block. Unless you have good reason to (e.g. keeping track of a counter), to place it outside is just bad practice.

Collapse
 
warrior97 profile image
warrior97

Also, don't know about javascript, some compilers optimise your code so that variable declarations inside a loop when turn to machine code are placed outside the 'loop'.
You can never know how a compiler will ootimise your code. Interpreters are a whole different story. Correct me if I'm wrong. There are other things you can do to optimise your code and better manage memory. First thing is algorithm complexity and storing excess data or use blocks of code so you limit the life of a variable and etc.

Thread Thread
 
jamesthomson profile image
James Thomson

There's definitely more important optimisations than worrying about a for loop. Unless you are looping through tens of thousands of objects - bit that's a whole different story.

Thread Thread
 
ahferroin7 profile image
Austin S. Hemmelgarn

If it were almost anything but memory allocation, I would agree wholeheartedly. Allocating memory, however, is literally one of the slowest runtime operations possible in pretty much any language you care to name (coincidentally, this is most of why C++'s std::string is so slow compared to C-style strings, pretty much any call that 'mutates' a string involves allocating memory for a new one).

The exact benefit may not be huge in terms of time, but it's a good habit to just write optimal code in cases like this where it's easy.

Thread Thread
 
ahferroin7 profile image
Austin S. Hemmelgarn

There are indeed other things you can do to optimize your code, but eliminating memory allocations (and de-allocations) is one of the easier ones that's consistently a win in most languages. That's one of the other reasons to group your variable declarations at the top of a function aside from making the code easier to read, some runtime environments and compilers will actually be able to further optimize things so that there are fewer allocations that need to be made that way.