JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Overview: Javascript Memory Leaks and Main Thread Bottleneck

--

There will come a point at least once in your career as a JavaScript developer where you’ll run into a memory leak issue (usually on production) and you’d be surprised to know that such a thing exists (and you’ve to take care of it). Lol. A moment that lets you transition to being a senior developer?

Recently, while working on ezCreatives I landed on one such problem.

Before: Notice how the main thread is always blocked. Tasks are getting sub-listed. (App gonna crash soon)
After: Notice the main thread is freed as soon as the task gets completed (though still room for improvement)

I am not actually going to explain any particular issue here but will point you to all the important links and resources you’ll need to understand, debug, and solve such issues in general. (Someday I might write a narrowed down article)

My problem somewhat looked like this. If you’re assigning a URL to any object like <a> or <img> tag using javascript, then make sure to revoke it after the use, else it causes a memory leak (URL gets attached to the scope of the whole document and won’t be garbage collected unless the document is destroyed)

Tools you need to know to solve for the Memory leak and CPU bottleneck issues (all are available in the browser’s developer tools):

  1. Performance section
  2. Memory section
  3. Lighthouse Audits

Most common types of memory leaks:

  1. Unintended Global Variables
  2. Unchecked timers or callbacks
  3. Detached DOM elements
  4. Closures

You can read about these common memory leak issues here, it’s explained comprehensively.

Main thread (CPU) bottleneck solutions

  1. Split up the long tasks (your as well as the third-party scripts)
  2. Run the chunks of code at the right time and the right place
  3. Use web workers to free your main thread (the ultimate)

Must have knowledge:

  1. How the renderer process works in the browser
  2. Javascript Event Loop and Promises
  3. Javascript Garbage Collection
  4. Developer tools

Conclusion

JavaScript is awesome. Use its power wisely. Will write a better conclusion someday.

Thanks for reading.

More content at plainenglish.io

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Vijay Pagare

Software Engineer | Frontend Developer | Open for opportunities

No responses yet

Write a response