Home > Software engineering >  Should I call new TextEncoder for the each encode operation?
Should I call new TextEncoder for the each encode operation?

Time:10-23

I want to get a Uint8Array representation of the string. Is it better to preallocate it once and reuse or to create a new one per the encoding?

function stringToUtf8ByteArray(str) {
    return new TextEncoder("utf-8").encode(str)
}
var TE = new TextEncoder("utf-8")
function stringToUtf8ByteArray(str) {
    return TE.encode(str)
}

I guess, there won't be any race conditions, because js is single threaded thing, isn't it?

CodePudding user response:

The TextEncoder doesn't contain anything that would make it costly to create, so the benefit of reusing an instance would be very small. The call to the encode method is doing the heavy lifting, so creating the TextEncoder each time would normally not be a concern.

You are right that there would be no race conditions if you were to preallocate the instance.

If you really need to trim the performance of the code, you should look into the encodeInto method, that places the result in an array that you provide. Reusing that array could do more for performance that reusing the TextEncoder instance.

The encodeInto method is currently not supported in Opera, so you would likely need the polyfill that is provided on the page that I linked to.

  • Related