DEV Community

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

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.