Skip to content

Commit 0927347

Browse files
riteshshukla04meta-codesync[bot]
authored andcommitted
perf: Cache normalisedColors output (#57896)
Summary: While looking into something I saw this processColor function , for every color we are calculating normalise Color even though it would have been done earlier. This is a simple approach. Maybe we can add things like LRU. With some simple scripts(Rendering around 1000 cells) I found around 13% faster . ## Changelog: <!-- Help reviewers and the release process by writing your own changelog entry. Pick one each for the category and type tags: [ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message For more details, see: https://reactnative.dev/contributing/changelogs-in-pull-requests --> [GENERAL][FIXED] - use cached results for already normalised colors Pull Request resolved: #57896 Test Plan: Tested in RN tester. Reviewed By: christophpurrer Differential Revision: D115779590 Pulled By: Abbondanzo fbshipit-source-id: a915bc641fbaff1055c18ac1efa20552a725102f
1 parent bc35168 commit 0927347

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

packages/normalize-color/index.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
'use strict';
1414

15+
const cachedColors = new Map();
16+
1517
function normalizeColor(color) {
1618
if (typeof color === 'number') {
1719
if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) {
@@ -24,6 +26,23 @@ function normalizeColor(color) {
2426
return null;
2527
}
2628

29+
if (cachedColors.has(color)) {
30+
// Map iteration order follows insertion order, so re-inserting on every
31+
// hit keeps the least-recently-used entry first.
32+
const cachedColor = cachedColors.get(color);
33+
cachedColors.delete(color);
34+
cachedColors.set(color, cachedColor);
35+
return cachedColor;
36+
}
37+
const normalizedColor = parseColorString(color);
38+
if (cachedColors.size >= 1024) {
39+
cachedColors.delete(cachedColors.keys().next().value);
40+
}
41+
cachedColors.set(color, normalizedColor);
42+
return normalizedColor;
43+
}
44+
45+
function parseColorString(color) {
2746
const matchers = getMatchers();
2847
let match;
2948

0 commit comments

Comments
 (0)