Skip to content

Commit 2091dcf

Browse files
authored
perf: reuse TextDecoder instance (#2863)
1 parent 7146587 commit 2091dcf

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

lib/web/websocket/receiver.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const { WebsocketFrameSend } = require('./frame')
1212
// Copyright (c) 2013 Arnout Kazemier and contributors
1313
// Copyright (c) 2016 Luigi Pinca and contributors
1414

15+
const textDecoder = new TextDecoder('utf-8', { fatal: true })
16+
1517
class ByteParser extends Writable {
1618
#buffers = []
1719
#byteOffset = 0
@@ -322,8 +324,7 @@ class ByteParser extends Writable {
322324
}
323325

324326
try {
325-
// TODO: optimize this
326-
reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
327+
reason = textDecoder.decode(reason)
327328
} catch {
328329
return null
329330
}

lib/web/websocket/util.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ function fireEvent (e, target, eventConstructor = Event, eventInitDict = {}) {
5555
target.dispatchEvent(event)
5656
}
5757

58+
const textDecoder = new TextDecoder('utf-8', { fatal: true })
59+
5860
/**
5961
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
6062
* @param {import('./websocket').WebSocket} ws
@@ -74,7 +76,7 @@ function websocketMessageReceived (ws, type, data) {
7476
// -> type indicates that the data is Text
7577
// a new DOMString containing data
7678
try {
77-
dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
79+
dataForEvent = textDecoder.decode(data)
7880
} catch {
7981
failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
8082
return

0 commit comments

Comments
 (0)