What's the Difference Between String Primitives and String Objects in JavaScript?
In JavaScript, primitives and objects are two distinct data types. String literals (e.g., "hello") and strings returned from String calls without the new keyword are primitive strings. However, JavaScript seamlessly converts primitives to String objects, enabling access to String object methods for primitive strings.
Auto-Boxing: A Key Insight
Understandably, one might assume that operations (method calls) on primitive strings would be slower than on String objects due to the extra conversion step. However, benchmark tests reveal the opposite, with primitive strings outperforming String objects in speed.
This counterintuitive behavior can be explained by auto-boxing. When a primitive string is used in an operation that requires a String object, JavaScript automatically wraps the primitive in a String object, invoking the required methods on the wrapped object.
Examining the Example
Consider the following code blocks:
// Code block-1: Primitive var s = '0123456789'; for (var i = 0; i < s.length; i++) { s.charAt(i); } // Code block-2: String object var s = new String('0123456789'); for (var i = 0; i < s.length; i++) { s.charAt(i); }
In code block-1, s is a primitive string, while in code block-2, s is a String object. Performance tests show that code block-1 consistently outperforms code block-2, regardless of the browser used.
Why the Performance Difference?
The performance benefit of primitive strings stems from their simpler data structure. Unlike String objects, primitive strings are pointers to raw memory locations, enabling faster random access.
When JavaScript automatically wraps a primitive string in a String object (auto-boxing), it incurs a slight performance penalty due to the object creation overhead. However, subsequent method calls on the auto-boxed string are still faster than using a String object directly because auto-boxing only applies the required methods without altering the primitive nature of the variable.
The above is the detailed content of Why Are JavaScript Primitive Strings Faster Than String Objects?. For more information, please follow other related articles on the PHP Chinese website!