Do common JavaScript implementations use string interning?

你说的曾经没有我的故事 提交于 2019-11-26 00:38:25

问题


Do common JavaScript engines, such as V8 and WebKit\'s JavaScriptCore, use string interning for JavaScript strings? Or do they actually keep multiple instances of identical strings in memory?


回答1:


Yes. In general any literal string, identifier, or other constant string in JS source is interned. However implementation details (exactly what is interned for instance) varies, as well as when the interning occurs.

Note that a string value is not the same as a String Object though, String Objects are not interned because that would be fundamentally incorrect behaviour.




回答2:


http://jsperf.com/strinterning

Yes in Chrome, no in Aurora 15 and FF 13! Comparing two strings is 85% slower than comparing two pointers in Firefox. However it's the same speed in Chrome, which is an indication that it is comparing two pointers.

Maybe the JS engine team at Mozilla should check their code...




回答3:


Short answer: sometimes yes, sometimes no.

I also stumbled upon the same question and looked a bit into it. It seems that interning is done usually for string primitives that are generated the same way (eg. always assigning the same string to a variable in the same loop), BUT I was also able to create an example which results in two identical strings being created with two different references:

As you can see, each string is stored twice, having different references.

This is the code I used to generate the duplicate strings:

const a = [];
const b = [];

for(let j  =1; j<= 100;++j){
    for(let i = 1; i <= 10000; ++i) a[i] = 'player 1 got 5 points from player 2' + i;
    for(let i = 1; i <= 10000; ++i) b[i] = 'player 1 got 5 points from player 2' + i;
}

It seems that string interning is done for string primitives, but not for concatenated strings, but as you can see above, each concatanated string only appears twice, not 100x2 = 200 times, so there is still string interning done for concatated strings created in the outer loop.



来源:https://stackoverflow.com/questions/5276915/do-common-javascript-implementations-use-string-interning

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