Skip to content

Commit

Permalink
Cache text encoding subarrays on-demand
Browse files Browse the repository at this point in the history
  • Loading branch information
valadaptive committed Sep 13, 2024
1 parent af6ceae commit 141eb72
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -469,16 +469,15 @@ if (typeof Buffer === 'function' && Buffer.prototype.utf8Slice) {
const ENCODER = new TextEncoder();
const encodeBuf = new Uint8Array(4096);
const encodeBufs = [];
// Believe it or not, `subarray` is actually quite expensive. To avoid the cost,
// we call `subarray` once for each possible slice length and reuse those cached
// views.
for (let i = 0; i <= encodeBuf.length; i++) {
encodeBufs.push(encodeBuf.subarray(0, i));
}

function encodeSlice(str) {
const {read, written} = ENCODER.encodeInto(str, encodeBuf);
if (read === str.length) {
// Believe it or not, `subarray` is actually quite expensive. To avoid the
// cost, we cache and reuse `subarray`s.
if (!encodeBufs[written]) {
encodeBufs[written] = encodeBuf.subarray(0, written);
}
return encodeBufs[written];
}

Expand Down

0 comments on commit 141eb72

Please sign in to comment.