In my career, I've worked a lot with different programming languages, especially with C# and javascript.
During my years of development, I've faced a lot of performance issues, on Mobile and Desktop applications.
Often, the main reasons for performances lack are scripts.
Scripts are the main part of our website/applications, they weight a lot and they use a lot of resources, like CPU and RAM.
In Javascript, there isn't a manual garbage collector system (like c# or c++ malloc or free method), so you need to optimize the resources management part of your application to prevent memory leaks, zombie data or other performance issues.
But what can we do, as developers, to decrease the RAM usage for example?
we need to write good code, reuse resources and handle data smartly.
For example, don't declare variables inside a for loop until it is really necessary!
Why
A for loop is a looped method invocation, so a variable declared inside a for loop will exists inside the loop scope only, and it will be initialized
in every loop iteration! This means than a space in memory for the variable will be allocated in each loop cycle!
What the heck!
This fact, combined with the typeless Js language could create big memory leaks, performance issues, and other bad behaviors.
A simple, but effective method to recycle RAM is to declare variables once and reuse them when needed. The for loop is the simplest case but you can replicate this solution everywhere.
Example
BAD
Declare cursor inside the for loop and a string inside too.
for (let i = 0; i < 1000; i++) {
let logString = 'Current is: ' + i;
console.log(logString);
}
console.log('%o', window.performance.memory);
{totalJSHeapSize: 68876822, usedJSHeapSize: 46264582, jsHeapSizeLimit: 2197815296}
GOOD
Declare cursor and logString outside the for loop:
let logString = '';
let i = 0;
for (i = 0; i < 1000; i++) {
logString = 'Current is: ' + i;
console.log(logString);
}
console.log('%o', window.performance.memory);
{totalJSHeapSize: 57747133, usedJSHeapSize: 45757109, jsHeapSizeLimit: 2197815296}
As you can see the totalJSHeapSize in the second implementation is less than the first one (< 11129689byte ~ 11mb), the usedJSHeapSize too (< 507473byte ~ 0.5mb).
I know, this isn't a great saving, but with large projects, this could save your web application performances!
Conclusion
There are a lot of optimization we can use to boost our applications, and this solution is not only JS-related, you could use it with any language you use.
But I think JS is the best case to use, because it's not resource-optimized.
I hope you found this article useful or just interesting!
Latest comments (45)
JavaScript hoists all function variables on top of the function. You can even define a variable at the end and it will still work. Also there is no block scope variables in JavaScript. Sorry but this article is wrong.
Although it's really great to point out and discuss low level performance concerns for things like loops...
The majority of the time it's better to have maintainable and readable code over optimized code. Compilers and garbage collectors usually do a good job most of the time!
IMO creating variables outside a loop for the sake of optimization adds code smells for little to no benefit!
Since you mentioned C#, it may be worth noting that you can define a C# variable within a loop without changing the resulting IL (the code that's actually run by the VM) at all. This is very easy to test.
However, there are instances, such as when using that variable within a lambda, in which this isn't true. That said, more often than not you actually should declare your variables inside the loop in C# so they are scoped properly.
Wtf dude delete it
You're implicitly assuming that JS is allocating stack variables similar to how a compiled language like C# does it. The interpreter in JS is running at a much higher level and if a variable is declared inside a loop it will effectively run the code as if the variable were declared outside. It won't do a reallocation like you would see in .NET bytecode.
Please don't do this and take this article down. As others have mentioned, the experiment is flawed.
Don't prematurely optimize. It can lead to a number of problems:
Don't complicate your code unless absolutely necessary. Follow the KISS principal.
I recently found myself reviewing code from a senior software engineer that was filled with premature optimizations. It was very hard to read and created an abundance of code for what purpose? Just to save a negligible amount of time - we're talking far less than a millisecond. Orders of magnitude less than your standard network delay.
Don't be that engineer.
Don't encourage others to be that engineer.
Like several people have said, this article needs to be updated with a disclaimer that it isn't accurate and the tests are far from comprehensive. Folks bookmarking this article are being mislead, and it's unfortunate for newer developers.
Thank you! This is exactly what I was looking to add.
I see what the OP is attempting to draw attention to: instantiating the variable every iteration seems wasteful... Of something. He drew attention to the one thing that seemed to stand out, memory. But in truth it's not that simple, as the comments have shown.
The better answer, if loop declaration us bothering you, is to put the variable declaration in a spot that it only happens once. Either in the declarative part of the if, like in the above comment, or the more verbose way of using an if to declare the variable on first run.
I suppose my question would be, how much garbage does it create if the "bad" loop were to run 1 million times? What about in a complex situation where the GC is somehow occupied, and this loop runs 1 million times?
For sure, more testing and fuzzing is needed before coming to a conclusion regarding the "bad" way.
Look, this article needs to be taken down. It's very harmful to novice programmers and more experienced programmers will probably just leave a comment saying "you're wrong". That being said, I feel bad for the author. He likely has no idea that this is bad advice and this is all probably discouraging. My advice for the author: please take the article down or revise it so that beginners don't draw incorrect conclusions. Afterwards, write your next article! I'd love to see you write about frontend or something else you're interested in!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.