-1

Worker.prototype.postMessage() can send JavaScript objects back to the UI thread. 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?

For example, imagine I invoke Worker.prototype.postMessage() with the following message:

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. Does that mean that 4 references will be created to one string:

  • on the worker's heap
  • in-transit as the message passes to the UI thread
  • at-rest when the message is received by the UI thread

Or is there any case where re-using a long string would cost me n * byteLengthOfString bytes?

In case it matters: I am targeting modern Chromium-based browsers.

Birchlabs
  • 5,931
  • 4
  • 28
  • 41

1 Answers1

1

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.)

That said: all of this is an implementation detail. It may well change over time. So this answer might become outdated in the future.

jmrk
  • 19,523
  • 5
  • 30
  • 43