Member-only story

Substrings are garbage

Why 13 characters can occupy megabytes of browser memory?

Marian C.
4 min readSep 13, 2021

In JavaScript, a string length and its size in memory do not always correlate. I mentioned in my previous posts that in JavaScript, depending on their characteristics and origins, strings can be represented as several C++ classes that to save memory and thus CPU time. 1 MB of memory might suffice to store a repetitive 512,000,000 characters long string. Usually such optimized strings get garbage collected without ever asking the browser to allocate individual memory bytes to their characters.

There is a dark side of such optimizations. Strings are quite efficient at causing memory leaks. To save time, a browser can keep in memory not anymore needed huge strings. A memory leak is a term for a condition where an application, instead of releasing unneeded memory, occupies additional memory. And as the application uses increasingly more memory, its performance gradually deteriorates. Other applications on the same computer also suffer because of the memory shortage.

Below I demonstrate how a browser keeps in memory an unnecessary string even when it is not explicitly referenced by any variables.

Evil substrings

In my experiment I will use the novel memory API that I described in detail in a previous

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

No responses yet