Skip to content

Instantly share code, notes, and snippets.

@dapplion
Last active October 15, 2020 08:25
Show Gist options
  • Save dapplion/5b4b4bee009fe5a5b596efed4b04a930 to your computer and use it in GitHub Desktop.
Save dapplion/5b4b4bee009fe5a5b596efed4b04a930 to your computer and use it in GitHub Desktop.
Benchmark Javascript binary equals
// Generate random data
const num = 1000000;
const dataArr: {a: Uint8Array; b: Uint8Array}[] = [];
const len = 32;
for (let i = 0; i < num; i++) {
const nums: number[] = [];
for (let j = 0; j < len; j++) {
nums[j] = j;
}
const a = new Uint8Array(nums);
const b = new Uint8Array(nums);
dataArr.push({a, b});
}
function equalsFor(a: Uint8Array, b: Uint8Array): boolean {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
function equalsEvery(a: Uint8Array, b: Uint8Array): boolean {
return a.every((v, i) => v === b[i]);
}
function equalsNode(a: Uint8Array, b: Uint8Array): boolean {
return Buffer.compare(Buffer.from(a), Buffer.from(b)) === 0;
}
// Run benchmarks
for (const [id, fn] of Object.entries({equalsFor, equalsEvery, equalsNode})) {
const label = `${num} - ${id}`;
console.time(label);
for (const {a, b} of dataArr) fn(a, b);
console.timeEnd(label);
}
// 1000000 - equalsFor: 132.577ms
// 1000000 - equalsEvery: 579.814ms
// 1000000 - equalsNode: 486.077ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment