Use LRU for encoded strings
Dan Abramov committed
Apr 15, 2019 at 14:41 UTC
255385d25545796023a049df65461abdd49a61be
1 file changed
+14
-1
src/utils.js
+14
-1
@@ -1,8 +1,14 @@
1
// @flow
2
3
+const LRU = require('lru-cache');
4
+
5
const FB_MODULE_RE = /^(.*) \[from (.*)\]$/;
6
const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();
7
8
+// On large trees, encoding takes significant time.
9
+// Try to reuse the already encoded strings.
10
+let encodedStringCache = new LRU({ max: 1000 });
11
+
12
export function getDisplayName(
13
type: Function,
14
fallbackName: string = 'Unknown'
@@ -56,8 +62,15 @@ export function utfDecodeString(array: Uint32Array): string {
62
}
63
64
export function utfEncodeString(string: string): Uint32Array {
65
+ let cached = encodedStringCache.get(string);
66
+ if (cached !== undefined) {
67
+ return cached;
68
+ }
69
+
70
// $FlowFixMe Flow's Uint32Array.from's type definition is wrong; first argument of mapFn will be string
60
- return Uint32Array.from(string, toCodePoint);
71
+ const encoded = Uint32Array.from(string, toCodePoint);
72
+ encodedStringCache.set(string, encoded);
73
+ return encoded;
74
}
75
76
function toCodePoint(string: string) {