Repository navigation
Commit 51f7828
committed
Look up a cached color without reordering the cache
Why
===
`normalizeColor` caches parsed color strings in a `Map` of up to 1,024 entries. Every hit deletes and re-inserts its entry to keep LRU order. That makes a hit cost three times what a single `get` would, and more than parsing a named color like `red`.
How
===
A hit is now a single `get`, and eviction is FIFO. Cached values are never `undefined`, so `get` alone tells a hit from a miss. A color in use is evicted after 1,024 newer strings and is then parsed again.
Instructions per `normalizeColor` call on Hermes, including about 75 for the benchmark loop:
| Color | Parsed | Cached, before | Cached, after |
| --- | ---: | ---: | ---: |
| `'#e5e5ea'` | 5,100 | 1,831 | 567 |
| `'red'` | 1,477 | 1,838 | 566 |
| `'rgba(0, 122, 255, 0.5)'` | 39,632 | 1,845 | 574 |
| `'hsl(120, 50%, 50%)'` | 23,926 | 1,833 | 567 |
| `'not a color'` | 12,199 | 1,830 | 575 |
Dropping LRU looks counterintuitive, but it is faster for most apps. LRU order only matters once the cache is full, and most apps use far fewer than 1,024 color strings.
As a real-world example, Bluesky's web app, browsed logged out in light and dark themes, used 64 distinct color strings across 49,021 calls.
Test Plan
=========
`yarn jest packages/normalize-color` passes, including a new test that a cached `0` or `null` is returned without parsing again. The instruction counts are from 200,000 calls under Hermes, minus a run with no calls, best of three.1 parent d1204ac commit 51f7828
2 files changed
Lines changed: 18 additions & 6 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
177 | 177 | | |
178 | 178 | | |
179 | 179 | | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| 185 | + | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
| 194 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
26 | 26 | | |
27 | 27 | | |
28 | 28 | | |
29 | | - | |
30 | | - | |
31 | | - | |
32 | | - | |
33 | | - | |
34 | | - | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
35 | 32 | | |
36 | 33 | | |
37 | 34 | | |
| |||
0 commit comments