常见的 JavaScript 实现是否使用字符串驻留?
常见的 JavaScript 引擎(例如 V8 和 WebKit 的 JavaScriptCore)是否对 JavaScript 字符串使用字符串驻留?或者他们实际上在内存中保存了相同字符串的多个实例吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。一般来说,JS 源中的任何文字字符串、标识符或其他常量字符串都会被保留。然而,实施细节(例如具体的实习内容)以及实习发生的时间各不相同。
请注意,字符串值与字符串对象不同,但字符串对象不会被保留,因为这从根本上来说是不正确的行为。
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.
http://jsperf.com/strinterning
在 Chrome 中可以,在 Aurora 15 和 FF 13 中不行!
在 Firefox 中比较两个字符串比比较两个指针慢 85%。
然而,Chrome 中的速度相同,这表明它正在比较两个指针。
也许 Mozilla 的 JS 引擎团队应该检查他们的代码......
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...
简短的回答:有时是,有时不是。
我也偶然发现了同样的问题并进行了一些研究。似乎实习通常是针对以相同方式生成的字符串文字完成的(例如,始终将相同的字符串分配给同一循环中的变量),但我还能够创建一个示例,该示例会导致创建两个相同的字符串有两个不同的引用:
如您所见,每个字符串存储两次,具有不同的引用。
这是我用来生成重复字符串的代码:
似乎字符串驻留是针对字符串文字完成的,而不是针对连接的字符串值完成的,但正如您在上面看到的,每个连接的字符串仅出现两次,而不是 100x2 = 200 次,因此,仍然对在外循环中创建的连接字符串进行字符串实习。
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 literals 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:
It seems that string interning is done for string literals, but not for concatenated string values, but as you can see above, each concatenated string only appears twice, not 100x2 = 200 times, so there is still string interning done for concatenated strings created in the outer loop.