mirror of
https://github.com/SukkaW/Surge.git
synced 2026-01-29 01:51:52 +08:00
Perf: optimize sort domains & preload promise
This commit is contained in:
@@ -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));
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user