How are strings saved in JavaScript ?

0
10
Adv1


Adv2

On this article, we’ll attempt to perceive how the Strings are saved in JavaScript. Strings are a primitive information kind in JavaScript and are allotted a particular place within the reminiscence to retailer and manipulate. The particular place allotted within the reminiscence is named String Fixed Pool. The string fixed pool is a small cache that resides throughout the heap. JavaScript shops all of the values contained in the string fixed pool on direct allocation.

In different phrases, the string fixed pool exists primarily to scale back reminiscence utilization and enhance the reuse of present situations in reminiscence. There are some instances the place we wish a definite String object to be created regardless that it has the identical worth. On this case, we use the new key phrase.

Allow us to now perceive with a primary instance, how strings are saved in reminiscence.

Instance 1: On this instance, we’ll create Strings and perceive how they’re saved in reminiscence.

Javascript

var str1 = "Hi there";

var str2 = "Hi there";

var str3 = "World";

console.log(str1 == str2);

console.log(str1 == str3);

Output:

true
false

Beneath is the diagrammatic illustration of how the strings within the above instance might be saved in reminiscence.

How are strings stored in javascript?

How are strings saved in javascript?

We are able to see that str1 and str2 level on the similar location within the reminiscence whereas a brand new house is created for str3 because it has a distinct worth. On this method string fixed pool saves reminiscence by making the identical worth string level to the identical location within the reminiscence.

Instance 2: On this instance, we’ll make the strings with the identical worth consult with totally different places in reminiscence

Javascript

var str1 = new String("John");

var str2 = new String("John");

var str3 = new String("Doe");

console.log(str1 == str2);

console.log(str1 == str3);

Output:

false
false
How are strings stored in javascript?

How are strings saved in javascript?

We are able to see within the picture that regardless that str1 and str2 are having the identical worth however due to the brand new key phrase they’re referring to totally different places within the reminiscence. Therefore, they return false in comparison.

Conclusion:

When creating the strings utilizing quotations(” “) they’re straight saved within the String Fixed Pool the place equal values consult with the identical location within the reminiscence. Whereas, when strings are created utilizing the brand new key phrase, a brand new occasion is at all times created within the heap reminiscence then the worth is saved within the String Fixed Pool due to this even when the info saved is similar nonetheless the strings won’t be equal.  

Adv3