Skip to content

Commit 0a73f97

Browse files
committed
chore: improve encode performance
1 parent 887d8a7 commit 0a73f97

1 file changed

Lines changed: 20 additions & 4 deletions

File tree

src/bytes.ts

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,34 @@ export function fromString (str: string): Uint8Array<ArrayBuffer> {
6464
return output
6565
}
6666

67+
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
68+
// the lowest limit is Chrome, with 0x10000 args.
69+
// We go 1 magnitude less, for safety
70+
const MAX_ARGUMENTS_LENGTH = 0x1000
71+
6772
/**
6873
* Convert the passed byte array to a string, interpreting each byte as a single
6974
* character
7075
*/
7176
export function toString (b: Uint8Array): string {
72-
let output = ''
77+
const len = b.length
7378

74-
for (let i = 0; i < b.length; i++) {
75-
output += String.fromCharCode(b[i])
79+
if (len <= MAX_ARGUMENTS_LENGTH) {
80+
// @ts-expect-error cannot ordinarily apply a Uint8Array
81+
return String.fromCharCode.apply(String, b) // avoid extra subarray()
7682
}
7783

78-
return output
84+
// Decode in chunks to avoid "call stack size exceeded".
85+
let res = ''
86+
let i = 0
87+
while (i < len) {
88+
res += String.fromCharCode.apply(
89+
String,
90+
// @ts-expect-error cannot ordinarily apply a Uint8Array
91+
b.subarray(i, i += MAX_ARGUMENTS_LENGTH)
92+
)
93+
}
94+
return res
7995
}
8096

8197
function isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {

0 commit comments

Comments
 (0)