New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
perf(ext/url): improve URLPattern perf #21488
Conversation
This significantly optimizes URLPattern in the case where the same URL is matched against many patterns (like in a router). Also minor speedups to other use-cases.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM, thanks for looking into this.
ext/url/01_urlpattern.js
Outdated
if (this.#lastUsedKey === key) return this.#lastUsedValue; | ||
const value = this.#map.get(key); | ||
if (value !== undefined) { | ||
if (MathRandom() < 0.1) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ideally should be actually do a least recently used strategy but fine for now. Maybe rename class to RandomLruCache
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It does do least recently used - maps are insertion ordered. See the code below this line (the re-insertion is to put the used item back to the "hot" side of the LRU), we use keys().next().value
to get item at the "cold" end of the LRU.
I am intentionally using a random chance to determine whether to refresh / insert as a very cheap pseudo "young space" where if a item is not used at least 10 times on average (but not 10 times in a row), it doesn't graduate into the more permanent LRU storage. This is done because inserting and refreshing LRU items is actually comparatively very expensive (about 50% of the operation it is caching).
This is a "pseudo young space" because it is random based, and thus sometimes misses the mark. In the benchmark configurations I have run that were written based on usage experience from real websites using Fresh (like dotcom), where there are some very hot routes, and a long tail of cold routes, I think this will do well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But yes, I can rename to SampledLruCache
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sounds good, thanks for explaning
This significantly optimizes URLPattern in the case where the same
URL is matched against many patterns (like in a router).
Also minor speedups to other use-cases.
Bench code: