简体   繁体   English

Web Worker postMessage 是否受益于字符串实习?

[英]Does Web Worker postMessage benefit from string interning?

Worker.prototype.postMessage() can send JavaScript objects back to the UI thread. Worker.prototype.postMessage()可以将 JavaScript 对象发送回 UI 线程。 It employs a Structured clone algorithm , which is capable of (for example) preserving cyclical references.它采用结构化克隆算法,该算法能够(例如)保留循环引用。

Does the structure produced by the structured clone algorithm have the string interning optimization applied to it?结构化克隆算法生成的结构是否应用了字符串驻留优化? When postMessage posts the structure to the main thread, does it send it in a way that preserves the reference re-use?postMessage将结构发布到主线程时,它是否以保留引用重用的方式发送它?

For example, imagine I invoke Worker.prototype.postMessage() with the following message:例如,假设我使用以下消息调用Worker.prototype.postMessage()

postMessage({
  superLongStringThatEnjoysFrequentUse: 'superLongStringThatEnjoysFrequentUse',
  also: [
    'superLongStringThatEnjoysFrequentUse',
    'superLongStringThatEnjoysFrequentUse'
  ]
})

How many times will I pay the price (in bytes) for my super long string?我将为我的超长字符串支付多少次价格(以字节为单位)?

The string is used 4 times in total.该字符串总共使用了 4 次。 Does that mean that 4 references will be created to one string:这是否意味着将为一个字符串创建 4 个引用:

  • on the worker's heap在工人堆上
  • in-transit as the message passes to the UI thread消息传递到 UI 线程时的传输中
  • at-rest when the message is received by the UI thread当 UI 线程接收到消息时处于静止状态

Or is there any case where re-using a long string would cost me n * byteLengthOfString bytes?或者在任何情况下重新使用长字符串会花费我n * byteLengthOfString字节?

In case it matters: I am targeting modern Chromium-based browsers.以防万一:我的目标是现代基于 Chromium 的浏览器。

The worker and the main thread definitely have at least one copy each, because their heaps are isolated from each other.工作线程和主线程肯定至少各有一个副本,因为它们的堆是相互隔离的。 The message itself does not use de-duplication for strings, so it will include several copies of the character data.消息本身不对字符串使用重复数据删除,因此它将包含多个字符数据副本。 The receiving side may apply interning later on, depending on what you do with the strings there.接收方稍后可能会申请实习,具体取决于您在那里处理字符串。 (The same is true for the sending side, or for apps that don't involve postMessage at all -- not all strings are interned because interning comes at a cost too, so it's easy to create a situation where you have several copies of the same string.) (对于发送方或根本不涉及postMessage的应用程序也是如此 - 并非所有字符串都被实习,因为实习也是有代价的,因此很容易造成您拥有多个副本的情况相同的字符串。)

That said: all of this is an implementation detail.也就是说:所有这些都是一个实现细节。 It may well change over time.它很可能会随着时间而改变。 So this answer might become outdated in the future.所以这个答案将来可能会过时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM