TL&DRs: What I know about JavaScript String.
Hey! What do you know about string
type in JavaScript? I believe you saw gazillion times about 1+'1'
or so. In this article, I won't talk about it, but I'd suggest we cover these questions:
How strings are stored?
Is there a limit for the string length?
Is it possible to overflow the call stack?
How are strings stored?
๐ Strings are stored in Heap. There is a special place for all the strings you're using: string pool:
Use DevTools console + memory tab to check how the string pool allocates memory:
Open
about://blank
pagePaste code like this (but do not execute it):
const a = 'hello'; const b = 'world'; const c = a + b; const d = 'hello'
-
Go to the memory tab and take the first heap snapshot. You will get something like this:
Execute the pasted code and take the second snapshot. You can compare snapshots using the select menu on top:
-
You can see that
hello
,world
and their concatenation were used only once.
Is there a limit for the string length?
๐ Yes, in V8 (node.js, chrome, etc.) there is a limit of 512Mb:
It was done by using:
const a = Array.from({length: MB64}).join('a')
b = a + a + a + a + a + a + a + a
Further increase in length would lead to the Invalid string length
exception:
๐ Be careful while processing big JSON entities or huge files in Node.JS or Chrome environment. You might need to use streams / binary blobs while reading data, instead of strings.
๐ Firefox at the same time doesn't have such a limit. You can see on a screenshot a string with about 1GB length:
Is it possible to overflow the stack using strings?
As strings are stored in a heap, the answer is no.
The only thing how you can overflow the stack is by creating too many references, like that:
More context about this trick: https://blog.xnim.me/js-call-stack-size-exceeded