What is string constant pool in JS ?
In this article i will try to explain how javascript deal with string in memory.
So first of all, Strings are a primitive data type which stored in a special place in memory called String Constant Pool.
The string constant pool is a small cache that resides within the heap.
let’s first check the normal assignment of a string as following:
let str1 = "Hello";
let str2 = "Hello";
let str3 = "World";
console.log(str1 == str2); // true
console.log(str1 == str3); // false
The above code is represent as following in memory:
We can see that str1 and str2 point at the same location in the memory while a new space is created for str3 as it has a different value. In this way string constant pool saves memory by making the same value string point to the same location in the memory.
Now, we have 2 ways to create string as following:
let userName= "Mohamed";
let userName2 = new String("Mohamed");
The difference between them is mainly reflected in the memory allocation.
We know that in JavaScript, all objects are reference types and they are allocated in heap memory.
At the same time, in order to efficiently process strings, the V8 engine maintains a string constant pool. Strings are stored in the string constant pool.
So the memory allocation diagram of the above code at runtime is as follows:
userName
refer to a string in string constant pool directly while userName2
refer to an object in heap as it’s created using new
keyword.
Anther example :
let userName = new String("Mohamed");
let userName1 = new String("Mohamed");
let userName2 = new String("Nour");
console.log(userName == userName1); //false
console.log(userName == userName2); //false
We can see in the image that even though userName
and userName1
are having the same value but because of the new keyword they are referring to different locations in the memory. Hence, they return false when compared.
Conclusion:
When creating the strings using quotations(” “) they are directly stored in the String Constant Pool where equal values refer to the same location in the memory. Whereas, when strings are created using the new keyword, a new instance is always created in the heap memory then the value is stored in the String Constant Pool because of this even if the data stored is the same still the strings will not be equal.