Skip to content

Commit 73c9984

Browse files
authored
Merge pull request #34 from sergeyzenchenko/master
Optimize string decoding performance
2 parents 65aa33b + 22e17a2 commit 73c9984

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/utils/utf8.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,20 @@ export function safeStringFromCharCode(units: Array<number> | Uint16Array) {
9898
return result;
9999
}
100100

101+
const MIN_TEXT_DECODER_STRING_LENGTH = 32;
102+
const defaultEncoding = "utf-8";
103+
const sharedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder(defaultEncoding) : null;
104+
101105
export function utf8Decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {
102106
let offset = inputOffset;
103-
const out: Array<number> = [];
104107
const end = offset + byteLength;
108+
109+
if (sharedTextDecoder !== null && byteLength > MIN_TEXT_DECODER_STRING_LENGTH) {
110+
const stringBytes = bytes.subarray(offset, end);
111+
return sharedTextDecoder.decode(stringBytes);
112+
}
113+
114+
const out: Array<number> = [];
105115
while (offset < end) {
106116
const byte1 = bytes[offset++];
107117
if ((byte1 & 0x80) === 0) {

0 commit comments

Comments
 (0)