Home > Net >  Javascript Webworker how to put json information into array buffer
Javascript Webworker how to put json information into array buffer

Time:12-23

I have thousands of small strings that I have to pass from a webworker back to the main page, each one is something like this:

"this string needs to be sent"

How would I be able to include it into an array buffer in order to increase the transfer speed? I understand how to use numbers with array buffers, but how do you use strings? I am looking for something like this:

var strings = ["str1","str2","str3",...]
for (var i = 0; i < strings.length; i  ) {
    arraybuffer[i] = //Whatever operation works to add strings[i]
}

CodePudding user response:

It's worth measuring and comparing performance of various techniques. The worker could use SharedArrayBuffer if supported in your target browsers (not exemplified below), otherwise Transferrable objects can be used with postMessage(). TextEncoder creates ArrayBuffers from strings.

Individual strings can be transferred as they are encoded:

const encoder = new TextEncoder()
strings.forEach(s => {
  const encoded = encoder.encode(s)
  postMessage(encoded, [encoded.buffer])
})

An array of strings could be transferred in batches:

const encoded = strings.map(s => encoder.encode(s))
postMessage(encoded, encoded.map(bytes => bytes.buffer))
  • Related