From 7ea7254513513d05c06be52a23de2740fc16a3ad Mon Sep 17 00:00:00 2001 From: Joe Lencioni Date: Sat, 4 Mar 2017 09:07:56 -0800 Subject: [PATCH] Optimize mapObj I did some profiling of StyleSheet.create and noticed that mapObj was a good target for optimization. Methodology I created an HTML document with the following code in it: ```html ``` Then, looking at the timeline tool in Chrome, I loaded the page a few times before and after this change. Similarly, I ran a CPU profile before and after this change through 5 page reloads each. In this test, the timeline was not very helpful, I think because of the testing overhead. However, the CPU profile was very clear. Before this change, normalizing for the callback showing up in a different part of the profile, `mapObj` took ~317ms and after this change, it drops to ~211ms. `StyleSheet.create` drops from ~755ms to ~670ms or roughly 11% faster. The rest of the time in `StyleSheet.create` is spent in `murmurhash2_32_gc` and `hashObject`. --- src/util.js | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/util.js b/src/util.js index c6e90c2..af4981b 100644 --- a/src/util.js +++ b/src/util.js @@ -10,19 +10,18 @@ type ObjectMap = { [id:string]: any }; // {K1: V1, K2: V2, ...} -> [[K1, V1], [K2, V2]] export const objectToPairs = (obj /* : ObjectMap */) /* : Pairs */ => Object.keys(obj).map(key => [key, obj[key]]); -// [[K1, V1], [K2, V2]] -> {K1: V1, K2: V2, ...} -const pairsToObject = (pairs /* : Pairs */) /* : ObjectMap */ => { - const result = {}; - pairs.forEach(([key, val]) => { - result[key] = val; - }); - return result; -}; - export const mapObj = ( obj /* : ObjectMap */, fn /* : PairsMapper */ -) /* : ObjectMap */ => pairsToObject(objectToPairs(obj).map(fn)) +) /* : ObjectMap */ => { + const keys = Object.keys(obj); + const mappedObj = {}; + for (let i = 0; i < keys.length; i += 1) { + const [newKey, newValue] = fn([keys[i], obj[keys[i]]]); + mappedObj[newKey] = newValue; + } + return mappedObj; +} // Flattens an array one level // [[A], [B, C, [D]]] -> [A, B, C, [D]]