DEV Community

A toddlers guide to memory leaks in Javascript

Kushan Joshi on February 05, 2018

In this article I will take a very simplistic approach in understanding memory leaks and I will also attempt to diagnose them. In todays world of ...
Collapse
 
ardennl profile image
Arden de Raaij

This is gold and exactly what I needed! I'm writing a thing on analyzing performance issues and I almost forgot about memory leaks. Thank you :).

Collapse
 
kepta profile image
Kushan Joshi

Thanks for your kind words.

Collapse
 
blouzada profile image
Bruno Louzada

Nice post! Chrome dev tools are awesome

Collapse
 
5bentz profile image
5bentz • Edited

result = newData.reduce((p,r) => arrayAddFirst(r, p), []);
virtual hug if you can guess what it does

I'd say it reverses the order of the elements.

for(var j = 0; j < i; i++)
Notice how easy it is to see it will run n * (n+1) / 2 times

To me, it is easy to see it is an infinite loop :'D
With j++, it would run 0 + 1 +...+ n-1 times. Thus, n*(n-1)/2 times.

This article is a simple tutorial to memory leak & its analysis in a web browser =) I used Firefox 60 instead of Chrome without any hassle.

Thank you !

Collapse
 
arielgueta profile image
Ariel Gueta • Edited

But after you invoke the function, the GC needs to collect it, no?

var hello = sayHi();
hello('Gandhi'); <=== I'm done
If we were in the global scope you are right, but if I'm within a scoped module, it will released the memory as soon as the second line execute.

Collapse
 
kepta profile image
Kushan Joshi

As long as the โ€˜helloโ€™ variable is in reference ( global or modular ), it will keep leaking memory.
You can run the hello function yourself and see memory usage increasing.

Collapse
 
rapasoft profile image
Pavol Rajzak

Thank you for very informative article!

Are you aware of any differences between JS engines when it comes to garbage collection?

Collapse
 
kepta profile image
Kushan Joshi • Edited

I am not sure, but yes the GC varies wrt engines. I have read this great article on V8 medium.com/@_lrlna/garbage-collect...

Hope it helps you.

Collapse
 
rapasoft profile image
Pavol Rajzak

That's actually quite nice article, thanks!

Collapse
 
liveabhishek profile image
Masterchief

Your example is really awesome. When I ran the example I found that old references were in (array) section. I sorted by Size Delta. Maybe due to different version of chrome.