From 2091dcfa1a9864dab7675be7c6bff34dbde06051 Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Tue, 27 Feb 2024 18:11:46 +0100 Subject: [PATCH] perf: reuse TextDecoder instance (#2863) --- lib/web/websocket/receiver.js | 5 +++-- lib/web/websocket/util.js | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/web/websocket/receiver.js b/lib/web/websocket/receiver.js index 63035618968..18dc474f16e 100644 --- a/lib/web/websocket/receiver.js +++ b/lib/web/websocket/receiver.js @@ -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 @@ -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 } diff --git a/lib/web/websocket/util.js b/lib/web/websocket/util.js index abe91be734d..8abe73c83e3 100644 --- a/lib/web/websocket/util.js +++ b/lib/web/websocket/util.js @@ -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 @@ -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