Primitive wrapper behavior in JavaScript

只谈情不闲聊 提交于 2019-12-10 21:53:34

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13035605/primitive-wrapper-behavior-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!