Skip to content

Commit

Permalink
Improve performance of compareUint8Arrays (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
hildjj authored Jan 6, 2024
1 parent b25ac06 commit b196c07
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
5 changes: 5 additions & 0 deletions benchmark.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {randomBytes} from 'node:crypto';
import benchmark from 'benchmark';
import {
base64ToString,
compareUint8Arrays,
concatUint8Arrays,
hexToUint8Array,
isUint8Array,
Expand All @@ -17,6 +18,8 @@ import {

const oneMb = 1024 * 1024;
const largeUint8Array = new Uint8Array(randomBytes(oneMb).buffer);
// eslint-disable-next-line unicorn/prefer-spread
const largeUint8ArrayDuplicate = largeUint8Array.slice();
const textFromUint8Array = uint8ArrayToString(largeUint8Array);
const base64FromUint8Array = Buffer.from(textFromUint8Array).toString('base64');
const hexFromUint8Array = uint8ArrayToHex(largeUint8Array);
Expand All @@ -25,6 +28,8 @@ const suite = new benchmark.Suite();

suite.add('isUint8Array', () => isUint8Array(largeUint8Array));

suite.add('compareUint8Arrays', () => compareUint8Arrays(largeUint8Array, largeUint8ArrayDuplicate));

suite.add('concatUint8Arrays with 2 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array]));

suite.add('concatUint8Arrays with 3 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array]));
Expand Down
19 changes: 4 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,26 +79,15 @@ export function compareUint8Arrays(a, b) {
const length = Math.min(a.length, b.length);

for (let index = 0; index < length; index++) {
if (a[index] < b[index]) {
return -1;
}

if (a[index] > b[index]) {
return 1;
const diff = a[index] - b[index];
if (diff !== 0) {
return Math.sign(diff);
}
}

// At this point, all the compared elements are equal.
// The shorter array should come first if the arrays are of different lengths.
if (a.length > b.length) {
return 1;
}

if (a.length < b.length) {
return -1;
}

return 0;
return Math.sign(a.length - b.length);
}

const cachedDecoder = new globalThis.TextDecoder();
Expand Down

0 comments on commit b196c07

Please sign in to comment.