From 092734772a2a17234491c3d86a3fba526d782175 Mon Sep 17 00:00:00 2001 From: riteshshukla04 Date: Thu, 13 Aug 2026 08:59:46 -0700 Subject: [PATCH] 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: [GENERAL][FIXED] - use cached results for already normalised colors Pull Request resolved: https://github.com/react/react-native/pull/57896 Test Plan: Tested in RN tester. Reviewed By: christophpurrer Differential Revision: D115779590 Pulled By: Abbondanzo fbshipit-source-id: a915bc641fbaff1055c18ac1efa20552a725102f --- packages/normalize-color/index.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/normalize-color/index.js b/packages/normalize-color/index.js index 67c5bdbb82e..05bdc3adc93 100644 --- a/packages/normalize-color/index.js +++ b/packages/normalize-color/index.js @@ -12,6 +12,8 @@ 'use strict'; +const cachedColors = new Map(); + function normalizeColor(color) { if (typeof color === 'number') { if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) { @@ -24,6 +26,23 @@ function normalizeColor(color) { return null; } + if (cachedColors.has(color)) { + // Map iteration order follows insertion order, so re-inserting on every + // hit keeps the least-recently-used entry first. + const cachedColor = cachedColors.get(color); + cachedColors.delete(color); + cachedColors.set(color, cachedColor); + return cachedColor; + } + const normalizedColor = parseColorString(color); + if (cachedColors.size >= 1024) { + cachedColors.delete(cachedColors.keys().next().value); + } + cachedColors.set(color, normalizedColor); + return normalizedColor; +} + +function parseColorString(color) { const matchers = getMatchers(); let match;