Perf: optimize sort domains & preload promise

This commit is contained in:
SukkaW
2024-01-14 23:29:29 +08:00
parent eaf993deca
commit 6daf8e3bb4
5 changed files with 48 additions and 31 deletions

View File

@@ -16,8 +16,9 @@ export const parseWithoutDetectIp = parse2;
let gothillGetDomainCache: ReturnType<typeof createCache> | null = null;
export const createCachedGorhillGetDomain = (gorhill: PublicSuffixList) => {
gothillGetDomainCache ??= createCache('cached-gorhill-get-domain', true);
return (domain: string) => {
gothillGetDomainCache ??= createCache('cached-gorhill-get-domain', true);
return gothillGetDomainCache.sync(domain, () => gorhill.getDomain(domain[0] === '.' ? domain.slice(1) : domain));
// we do know gothillGetDomainCache exists here
return gothillGetDomainCache!.sync(domain, () => gorhill.getDomain(domain[0] === '.' ? domain.slice(1) : domain));
};
};

View File

@@ -1,7 +1,12 @@
export const createMemoizedPromise = <T>(fn: () => Promise<T>): () => Promise<T> => {
export const createMemoizedPromise = <T>(fn: () => Promise<T>, preload = true): () => Promise<T> => {
let promise: Promise<T> | null = null;
if (preload) {
promise = fn();
}
return () => {
promise ||= fn();
promise ??= fn();
return promise;
};
};

View File

@@ -35,18 +35,14 @@ const compare = (a: string | null, b: string | null) => {
export const sortDomains = (inputs: string[], gorhill: PublicSuffixList) => {
const getDomain = createCachedGorhillGetDomain(gorhill);
const domains = inputs.reduce<Record<string, string>>((acc, cur) => {
acc[cur] ||= getDomain(cur);
const domains = inputs.reduce<Map<string, string>>((acc, cur) => {
if (!acc.has(cur)) acc.set(cur, getDomain(cur));
return acc;
}, {});
}, new Map());
const sorter = (a: string, b: string) => {
if (a === b) return 0;
const aDomain = domains[a];
const bDomain = domains[b];
return compare(aDomain, bDomain) || compare(a, b);
return compare(domains.get(a)!, domains.get(b)!) || compare(a, b);
};
return inputs.sort(sorter);