JavaScript – Memory Usage of String Type with Identical Values

javascriptmemory usagestrings

JavaScript string type is immutable, but does it mean identical strings will share memory?

Say two strings are created in complete different places, will a modern JavaScript engine be smart enough to not double the amount of memory for each "copy" and just re-use the one already created (that exists somewhere in memory)?

Say we got:

var foo = sha256(fooInput); 
//  ... somewhere else
var bar = sha256(barInput);

// Say foo and bar is identical: "foo === bar" => true
// Would they share memory? 

Does it make any difference if the string value is a key in objects? Example:

var cars = {
  "john": {
    // information about all cars "john" owns.
  }
};

var computers = {
  "john": {
    // information about all computers "john" owns.
  }
};

var phones = {
  "john": {
    // information about all phones "john" owns.
  }
};

Will the string "john" in the example above take up memory of three or one string of "john"?

Best Answer

The process of sharing strings in this manner is called String Interning, and yes, Javascript does it. The way in which string interning is accomplished in Javascript is an implementation detail, and it varies between different Javascript implementations.

From a performance perspective, you probably shouldn't be worrying about this unless it becomes a significant problem affecting your application that you have specifically identified with a profiling tool.

Related Topic