Perf: use Bun.peek() to save a few ticks

This commit is contained in:
SukkaW
2024-01-28 22:29:14 +08:00
parent c95e96fc61
commit e626a6b5d2
13 changed files with 108 additions and 47 deletions

View File

@@ -158,9 +158,21 @@ export class Cache {
let value: T;
if (cached == null) {
console.log(picocolors.yellow('[cache] miss'), picocolors.gray(key), picocolors.gray(`ttl: ${TTL.humanReadable(ttl)}`));
value = await fn();
const serializer = 'serializer' in opt ? opt.serializer : identity;
const promise = fn();
const peeked = Bun.peek(promise);
if (peeked === promise) {
return promise.then((value) => {
const serializer = 'serializer' in opt ? opt.serializer : identity;
this.set(key, serializer(value), ttl);
return value;
});
}
value = peeked as T;
this.set(key, serializer(value), ttl);
} else {
console.log(picocolors.green('[cache] hit'), picocolors.gray(key));
@@ -168,6 +180,7 @@ export class Cache {
const deserializer = 'deserializer' in opt ? opt.deserializer : identity;
value = deserializer(cached);
}
return value;
}

View File

@@ -13,6 +13,7 @@ import type { Span } from '../trace';
const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
let foundDebugDomain = false;
const temporaryBypass = DEBUG_DOMAIN_TO_FIND !== null;
export function processDomainLists(span: Span, domainListsUrl: string, includeAllSubDomain = false, ttl: number | null = null) {
return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn(() => fsFetchCache.apply(
@@ -38,7 +39,7 @@ export function processDomainLists(span: Span, domainListsUrl: string, includeAl
},
{
ttl,
temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
temporaryBypass,
serializer: serializeSet,
deserializer: deserializeSet
}
@@ -97,7 +98,7 @@ export function processHosts(span: Span, hostsUrl: string, mirrors: string[] | n
},
{
ttl,
temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
temporaryBypass,
serializer: serializeSet,
deserializer: deserializeSet
}
@@ -131,7 +132,11 @@ export async function processFilterRules(
const warningMessages: string[] = [];
const gorhill = await getGorhillPublicSuffixPromise();
const gorhillPromise = getGorhillPublicSuffixPromise();
const peekedGorhill = Bun.peek(gorhillPromise);
const gorhill = peekedGorhill === gorhillPromise
? await span.traceChild('get gorhill').tracePromise(gorhillPromise)
: (peekedGorhill as PublicSuffixList);
/**
* @param {string} line
@@ -215,7 +220,7 @@ export async function processFilterRules(
},
{
ttl,
temporaryBypass: DEBUG_DOMAIN_TO_FIND !== null,
temporaryBypass,
serializer: JSON.stringify,
deserializer: JSON.parse
}