Question

In the book Professional Javascript for Web Developers i read that primitive wrappers are used internally by JavaScript when trying to access properties and methods of primitive objects. Does that mean that each time i try to access the length property on a string primitive the value is recalculated? My gut tells me that since strings are fixed then their length value is stored somewhere and only accessed by the wrapper, but i'd rather be sure.

Was it helpful?

Solution

I think that's true, primitive wrappers are created on the fly when you try to access properties of primitive values, like this:

"foo".length; // behaves as new String('foo').length

Not only the length is calculated on the moment you try to access the property, but a whole new object is created too (that object is what actually contains the property). The wrapper is then discarded immediately.

If you're worried about performance, don't be. There's rarely a case when you must use a primitive wrapper object, and their performance seems to be orders of magnitude slower than just using the primitive values (see test). Let the interpreter care about optimization.

OTHER TIPS

By specification, yes (§11.2.1, §8.7.1, §9.9, §15.5.5).

Still that does not mean an actual implementation will create string objects in the memory, this is surely optimized.

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