Revert "refactor(bytes): remove equalsNaive (#2852)" (#2854)

This commit is contained in:
Yoshiya Hinosawa 2022-11-09 00:17:16 +09:00 committed by GitHub
parent b7e9dee53c
commit b23cf6aac8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 60 additions and 2 deletions

View File

@ -1,11 +1,25 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/** Check whether binary arrays are equal to each other.
/** Check whether binary arrays are equal to each other using 8-bit comparisons.
* @private
* @param a first array to check equality
* @param b second array to check equality
*/
export function equals(a: Uint8Array, b: Uint8Array): boolean {
export function equalsNaive(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < b.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
/** Check whether binary arrays are equal to each other using 32-bit comparisons.
* @private
* @param a first array to check equality
* @param b second array to check equality
*/
export function equals32Bit(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
const len = a.length;
const compressable = Math.floor(len / 4);
@ -19,3 +33,12 @@ export function equals(a: Uint8Array, b: Uint8Array): boolean {
}
return true;
}
/** Check whether binary arrays are equal to each other.
* @param a first array to check equality
* @param b second array to check equality
*/
export function equals(a: Uint8Array, b: Uint8Array): boolean {
if (a.length < 1000) return equalsNaive(a, b);
return equals32Bit(a, b);
}

35
bytes/equals_bench.ts Normal file
View File

@ -0,0 +1,35 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { equals32Bit, equalsNaive } from "./equals.ts";
console.log("generating benchmarks...");
const testCases: [Uint8Array, Uint8Array][] = [];
// CHANGE THESE
const len = 10000;
const nCases = 10000;
for (let i = 0; i < nCases; i++) {
const arr1 = crypto.getRandomValues(new Uint8Array(len));
const arr2 = crypto.getRandomValues(new Uint8Array(len));
const arr3 = arr1.slice(0);
arr3[arr3.length - 1] = arr1[arr1.length - 1] ^ 1;
testCases.push([arr1, arr1.slice(0)]);
testCases.push([arr1, arr2]);
testCases.push([arr1, arr3]);
}
Deno.bench({
name: "bench old equals",
fn() {
for (const [a, b] of testCases) {
equalsNaive(a, b);
}
},
});
Deno.bench({
name: "bench simd equals",
fn() {
for (const [a, b] of testCases) {
equals32Bit(a, b);
}
},
});