Skip to content

Commit

Permalink
Perf: reduce comparision in domain sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed May 2, 2024
1 parent e5d511d commit a0b06d8
Showing 1 changed file with 53 additions and 12 deletions.
65 changes: 53 additions & 12 deletions Build/lib/stable-sort-domain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
import { createCachedGorhillGetDomain } from './cached-tld-parse';

class TwoKeyCache {
private cache: Map<string, Map<string, number>>;
public hitCount = 0;

constructor() {
this.cache = new Map();
}

apply(a: string, b: string, fn: (a: string, b: string) => number): number {
let r = this.get(a, b);
if (r !== undefined) {
this.hitCount++;
return r;
}

r = fn(a, b);
this.set(a, b, r);
this.set(b, a, -1 * r);
return r;
}

private get(a: string, b: string): number | undefined {
return this.cache.get(a)?.get(b);
}

private set(a: string, b: string, value: number): void {
let innerCache = this.cache.get(a);
if (!innerCache) {
innerCache = new Map();
this.cache.set(a, innerCache);
}
innerCache.set(b, value);
}
}

const compare = (a: string | null, b: string | null) => {
if (a === b) return 0;
if (b == null) {
Expand All @@ -12,17 +47,19 @@ const compare = (a: string | null, b: string | null) => {

const aLen = a.length;
const r = aLen - b.length;
if (r > 0) {
return 1;
}
if (r < 0) {
return -1;
}
// if (r > 0) {
// return 1;
// }
// if (r < 0) {
// return -1;
// }
if (r !== 0) return r;

for (let i = 0; i < aLen; i++) {
if (b[i] == null) {
return 1;
}
// if (!b[i]) {
// return 1;
// }
// Since aLen === b.length, we don't need to check b[i] here
if (a[i] < b[i]) {
return -1;
}
Expand All @@ -40,6 +77,8 @@ export const sortDomains = (inputs: string[], gorhill: PublicSuffixList) => {
return acc;
}, new Map());

const cache = new TwoKeyCache();

const sorter = (a: string, b: string) => {
if (a === b) return 0;

Expand All @@ -48,10 +87,12 @@ export const sortDomains = (inputs: string[], gorhill: PublicSuffixList) => {

// avoid compare same thing twice
if (a === $a && b === $b) {
return compare(a, b);
return cache.apply(a, b, compare);
}
return compare($a, $b) || compare(a, b);
return cache.apply($a, $b, compare) || cache.apply(a, b, compare);
};

return inputs.sort(sorter);
const r = inputs.sort(sorter);
console.log('hit count', cache.hitCount);
return r;
};

0 comments on commit a0b06d8

Please sign in to comment.