Skip to content

Commit

Permalink
perf: reuse TextDecoder instance (#2863)
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak authored Feb 27, 2024
1 parent 7146587 commit 2091dcf
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lib/web/websocket/receiver.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const { WebsocketFrameSend } = require('./frame')
// Copyright (c) 2013 Arnout Kazemier and contributors
// Copyright (c) 2016 Luigi Pinca and contributors

const textDecoder = new TextDecoder('utf-8', { fatal: true })

class ByteParser extends Writable {
#buffers = []
#byteOffset = 0
Expand Down Expand Up @@ -322,8 +324,7 @@ class ByteParser extends Writable {
}

try {
// TODO: optimize this
reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
reason = textDecoder.decode(reason)
} catch {
return null
}
Expand Down
4 changes: 3 additions & 1 deletion lib/web/websocket/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ function fireEvent (e, target, eventConstructor = Event, eventInitDict = {}) {
target.dispatchEvent(event)
}

const textDecoder = new TextDecoder('utf-8', { fatal: true })

/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
* @param {import('./websocket').WebSocket} ws
Expand All @@ -74,7 +76,7 @@ function websocketMessageReceived (ws, type, data) {
// -> type indicates that the data is Text
// a new DOMString containing data
try {
dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
dataForEvent = textDecoder.decode(data)
} catch {
failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
return
Expand Down

0 comments on commit 2091dcf

Please sign in to comment.