From c9ff8b35c238cedd9b5b72daa41b5de77cac3a37 Mon Sep 17 00:00:00 2001 From: bkmartinjr Date: Mon, 7 May 2018 15:13:50 -0700 Subject: [PATCH 1/2] Perf - cache parsed color descriptions --- src/util/parseRGB.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/util/parseRGB.js b/src/util/parseRGB.js index bdd9ebee..1e36beb8 100644 --- a/src/util/parseRGB.js +++ b/src/util/parseRGB.js @@ -1,7 +1,13 @@ // jshint esversion: 6 import { scaleRGB } from "./scaleRGB"; -export const parseRGB = c => { +// maintain a cache of already parsed RGB names, as it is reasonably expensive +// to do this operation. This lets us have speed, but keep the pleasant ability +// to talk about colors by their text description eg, 'rgb(0,0,1)' +// +const colorCache = new Map(); + +function parseColorName(c) { if (c[0] !== "#") { const _c = c.replace(/[^\d,.]/g, "").split(","); return [scaleRGB(+_c[0]), scaleRGB(+_c[1]), scaleRGB(+_c[2])]; @@ -13,4 +19,13 @@ export const parseRGB = c => { scaleRGB(parseInt(parsedHex[3], 16)) ]; } +} + +export const parseRGB = c => { + var cv = colorCache.get(c); + if (!cv) { + cv = parseColorName(c); + colorCache.set(c, cv); + } + return cv; }; From 783b7a46f15bfe12515c18235bc8ed16478da926 Mon Sep 17 00:00:00 2001 From: bkmartinjr Date: Tue, 8 May 2018 10:31:42 -0700 Subject: [PATCH 2/2] use Object rather than Map to store color cache --- src/util/parseRGB.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/util/parseRGB.js b/src/util/parseRGB.js index 1e36beb8..9d0f9f16 100644 --- a/src/util/parseRGB.js +++ b/src/util/parseRGB.js @@ -5,7 +5,7 @@ import { scaleRGB } from "./scaleRGB"; // to do this operation. This lets us have speed, but keep the pleasant ability // to talk about colors by their text description eg, 'rgb(0,0,1)' // -const colorCache = new Map(); +const colorCache = new Object(null); // no prototype function parseColorName(c) { if (c[0] !== "#") { @@ -22,10 +22,10 @@ function parseColorName(c) { } export const parseRGB = c => { - var cv = colorCache.get(c); + var cv = colorCache[c]; if (!cv) { cv = parseColorName(c); - colorCache.set(c, cv); + colorCache[c] = cv; } return cv; };