From 78ecc4cfd096cc5e8434f613ec7044c41f874f78 Mon Sep 17 00:00:00 2001 From: ptaylor Date: Wed, 9 Jan 2019 09:26:26 -0800 Subject: [PATCH] use the textencoders from the global instead of Buffer for perf testing --- js/src/util/utf8.ts | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/js/src/util/utf8.ts b/js/src/util/utf8.ts index cae3b9960ca9d..b1d2c8eb745e0 100644 --- a/js/src/util/utf8.ts +++ b/js/src/util/utf8.ts @@ -21,20 +21,27 @@ import { TextEncoder as TextEncoderPolyfill, } from 'text-encoding-utf-8'; +/** @suppress {missingRequire} */ +const _Buffer = typeof Buffer === 'function' ? Buffer : null; +const useNativeEncoders = typeof TextDecoder === 'function' && typeof TextEncoder === 'function'; + /** @ignore */ -export const decodeUtf8 = ((decoder) => { - /** @suppress {missingRequire} */ - const NodeBuffer = typeof Buffer !== 'undefined' ? Buffer : null; - return !NodeBuffer ? decoder.decode.bind(decoder) : (input: ArrayBufferLike | ArrayBufferView) => { +export const decodeUtf8 = ((TextDecoder) => { + if (useNativeEncoders || !_Buffer) { + const decoder = new TextDecoder(); + return decoder.decode.bind(decoder); + } + return (input: ArrayBufferLike | ArrayBufferView) => { const { buffer, byteOffset, length } = toUint8Array(input); - return NodeBuffer.from(buffer, byteOffset, length).toString(); + return _Buffer.from(buffer, byteOffset, length).toString(); }; -})(new (typeof TextDecoder !== 'undefined' ? TextDecoder : TextDecoderPolyfill)()); +})(typeof TextDecoder !== 'undefined' ? TextDecoder : TextDecoderPolyfill); /** @ignore */ -export const encodeUtf8 = ((encoder) => { - /** @suppress {missingRequire} */ - const NodeBuffer = typeof Buffer !== 'undefined' ? Buffer : null; - return !NodeBuffer ? encoder.encode.bind(encoder) : - (input = '') => toUint8Array(NodeBuffer.from(input, 'utf8')); -})(new (typeof TextEncoder !== 'undefined' ? TextEncoder : TextEncoderPolyfill)()); +export const encodeUtf8 = ((TextEncoder) => { + if (useNativeEncoders || !_Buffer) { + const encoder = new TextEncoder(); + return encoder.encode.bind(encoder); + } + return (input = '') => toUint8Array(_Buffer.from(input, 'utf8')); +})(typeof TextEncoder !== 'undefined' ? TextEncoder : TextEncoderPolyfill);