Skip to content

Commit b196c07

Browse files
authored
Improve performance of compareUint8Arrays (#8)
1 parent b25ac06 commit b196c07

File tree

2 files changed

+9
-15
lines changed

2 files changed

+9
-15
lines changed

benchmark.mjs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {randomBytes} from 'node:crypto';
55
import benchmark from 'benchmark';
66
import {
77
base64ToString,
8+
compareUint8Arrays,
89
concatUint8Arrays,
910
hexToUint8Array,
1011
isUint8Array,
@@ -17,6 +18,8 @@ import {
1718

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

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

31+
suite.add('compareUint8Arrays', () => compareUint8Arrays(largeUint8Array, largeUint8ArrayDuplicate));
32+
2833
suite.add('concatUint8Arrays with 2 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array]));
2934

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

index.js

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -79,26 +79,15 @@ export function compareUint8Arrays(a, b) {
7979
const length = Math.min(a.length, b.length);
8080

8181
for (let index = 0; index < length; index++) {
82-
if (a[index] < b[index]) {
83-
return -1;
84-
}
85-
86-
if (a[index] > b[index]) {
87-
return 1;
82+
const diff = a[index] - b[index];
83+
if (diff !== 0) {
84+
return Math.sign(diff);
8885
}
8986
}
9087

9188
// At this point, all the compared elements are equal.
9289
// The shorter array should come first if the arrays are of different lengths.
93-
if (a.length > b.length) {
94-
return 1;
95-
}
96-
97-
if (a.length < b.length) {
98-
return -1;
99-
}
100-
101-
return 0;
90+
return Math.sign(a.length - b.length);
10291
}
10392

10493
const cachedDecoder = new globalThis.TextDecoder();

0 commit comments

Comments
 (0)