Skip to content Skip to sidebar Skip to footer

Primitive Wrapper Behavior In Javascript

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 ob

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Primitive Wrapper Behavior In Javascript"