Skip to content

Commit

Permalink
Optimize serializing SharedArrayBuffers for zero values [perf]
Browse files Browse the repository at this point in the history
  • Loading branch information
overlookmotel committed Oct 1, 2023
1 parent 86909b7 commit ab69f08
Showing 1 changed file with 19 additions and 20 deletions.
39 changes: 19 additions & 20 deletions lib/serialize/buffers.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,33 +158,32 @@ registerSerializer(ARRAY_BUFFER_TYPE, serializeArrayBuffer);
function serializeSharedArrayBuffer(record) {
const uint = new Uint8Array(record.extra.buf);

let valNodes,
numTrailingZeros = 0,
firstNonZeroIndex = 0;
uint.forEach((val, index) => {
if (val !== 0) {
if (!valNodes) {
valNodes = [];
firstNonZeroIndex = index;
}
valNodes.push(t.numericLiteral(val));
numTrailingZeros = 0;
} else if (valNodes) {
valNodes.push(null);
numTrailingZeros++;
}
});

// `new SharedArrayBuffer(8)`
const len = uint.length;
const node = t.newExpression(
this.traceAndSerializeGlobal(SharedArrayBuffer),
[t.numericLiteral(uint.length)]
[t.numericLiteral(len)]
);

if (valNodes) {
// `new Uint8Array(arr).set([1, 2, 3]);`
// Set non-zero values (if any)
const firstNonZeroIndex = uint.findIndex(byte => byte !== 0);
if (firstNonZeroIndex !== -1) {
const valNodes = [];
let numTrailingZeros = 0;
for (let index = firstNonZeroIndex; index < len; index++) {
const val = uint[index];
if (val === 0) {
valNodes.push(null);
numTrailingZeros++;
} else {
valNodes.push(t.numericLiteral(val));
numTrailingZeros = 0;
}
}

if (numTrailingZeros > 0) valNodes.length -= numTrailingZeros;

// `new Uint8Array(arr).set([1, 2, 3]);`
this.assignmentNodes.push(
t.expressionStatement(
t.callExpression(
Expand Down

0 comments on commit ab69f08

Please sign in to comment.