Skip to content

Commit 26990fd

Browse files
committed
perf: optimize toHex on old browsers
1 parent b0772e4 commit 26990fd

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

fallback/hex.js

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { assertUint8 } from '../assert.js'
2-
import { nativeEncoder } from './_utils.js'
2+
import { nativeDecoder, nativeEncoder } from './_utils.js'
33

4-
let hexArray
4+
let hexArray // array of 256 bytes converted to two-char hex strings
5+
let hexCodes // hexArray converted to u16 code pairs
56
let dehexArray
67
const _00 = 0x30_30 // '00' string in hex, the only allowed char pair to generate 0 byte
78
const _ff = 0x66_66 // 'ff' string in hex, max allowed char pair (larger than 'FF' string)
@@ -63,6 +64,24 @@ export function toHex(arr) {
6364
if (!hexArray) hexArray = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'))
6465
const length = arr.length // this helps Hermes
6566

67+
// Only old browsers use this, barebone engines don't have TextDecoder
68+
// But Hermes can use this when it (hopefully) implements TextDecoder
69+
if (nativeDecoder) {
70+
if (!hexCodes) {
71+
hexCodes = new Uint16Array(256)
72+
const u8 = new Uint8Array(hexCodes.buffer, hexCodes.byteOffset, hexCodes.byteLength)
73+
for (let i = 0; i < 256; i++) {
74+
const pair = hexArray[i]
75+
u8[2 * i] = pair.charCodeAt(0)
76+
u8[2 * i + 1] = pair.charCodeAt(1)
77+
}
78+
}
79+
80+
const pairs = new Uint16Array(length)
81+
for (let i = 0; i < length; i++) pairs[i] = hexCodes[arr[i]]
82+
return nativeDecoder.decode(new Uint8Array(pairs.buffer, pairs.byteOffset, pairs.byteLength))
83+
}
84+
6685
if (length > 30_000) {
6786
// Limit concatenation to avoid excessive GC
6887
// Thresholds checked on Hermes

0 commit comments

Comments
 (0)