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!
Why? JavaScript has automatic garbage collection mechanism.