Question

For example, suppose I have a long string primitive called str. I know I can use str.substr because the browser, behind the scenes,

  1. Converts str into a string wrapper object, equivalent to using new String(str)
  2. Calls the substr method with the correct parameters on the String object returned by step 1
  3. Disposes of the String object
  4. Returns the string (primitive) from step 2.

(https://stackoverflow.com/a/9110389/1529630)

But what happens if I want to use str.substr lots of times? For example

var positions = [1, 5, 8, 9, 15, ...],    //long array
    substrings = new Array(positions.length);

for ( var i = positions.length - 1;  i >= 0;  --i ) {
    substrings[i] = str.substr(positions[i], 2);
}

Should I convert str to an object before that loop in order to avoid creating and destroying an object at every step?

Was it helpful?

Solution

There's a blog entry dedicated to that question here.

In short, working with primitive values is faster most of the time because of optimizations made by most JS engines. However, that might not be the case when accessing non-native members on primitives.

For instance, we can read in the article that:

In the SpiderMonkey JS engine, for example, the pseudo-code that deals with the “get property” operation looks something like the following:

  // direct check for the "length" property
  if (typeof(value) == "string" && property == "length") {
    return StringLength(value);
  }
  // generalized code form for properties
  object = ToObject(value);
  return InternalGetProperty(object, property);

Thus, when you request a property on a string primitive, and the property name is “length”, the engine immediately just returns its length, avoiding the full property lookup as well as the temporary wrapper object creation.

Here's the conclusion:

Based on the benchmarks described above, we have seen a number of ways about how subtle differences in our string declarations can produce a series of different performance results. It is recommended that you continue to declare your string variables as you normally do, unless there is a very specific reason for you to create instances of the String Object. Also, note that a browser’s overall performance, particularly when dealing with the DOM, is not only based on the page’s JS performance; there is a lot more in a browser than its JS engine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top