DEV Community

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

 
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.