Skip to content

Commit b2553f3

Browse files
author
Brian Vaughn
committed
Re-added encoded string LRU cache
1 parent f16251a commit b2553f3

File tree

1 file changed

+20
-6
lines changed
  • packages/react-devtools-shared/src

1 file changed

+20
-6
lines changed

packages/react-devtools-shared/src/utils.js

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* @flow
88
*/
99

10+
import LRU from 'lru-cache';
1011
import {
1112
isElement,
1213
typeOf,
@@ -49,9 +50,16 @@ import {localStorageGetItem, localStorageSetItem} from './storage';
4950
import {meta} from './hydration';
5051

5152
import type {ComponentFilter, ElementType} from './types';
53+
import type {LRUCache} from 'react-devtools-shared/src/types';
5254

5355
const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();
5456

57+
// On large trees, encoding takes significant time.
58+
// Try to reuse the already encoded strings.
59+
const encodedStringCache: LRUCache<string, Array<number>> = new LRU({
60+
max: 1000,
61+
});
62+
5563
export function alphaSortKeys(
5664
a: string | number | Symbol,
5765
b: string | number | Symbol,
@@ -140,21 +148,27 @@ function surrogatePairToCodePoint(
140148
// Credit for this encoding approach goes to Tim Down:
141149
// https://stackoverflow.com/questions/4877326/how-can-i-tell-if-a-string-contains-multibyte-characters-in-javascript
142150
export function utfEncodeString(string: string): Array<number> {
143-
const codePoints = [];
151+
const cached = encodedStringCache.get(string);
152+
if (cached !== undefined) {
153+
return cached;
154+
}
155+
156+
const encoded = [];
144157
let i = 0;
145158
let charCode;
146159
while (i < string.length) {
147160
charCode = string.charCodeAt(i);
148161
if ((charCode & 0xf800) === 0xd800) {
149-
codePoints.push(
150-
surrogatePairToCodePoint(charCode, string.charCodeAt(++i)),
151-
);
162+
encoded.push(surrogatePairToCodePoint(charCode, string.charCodeAt(++i)));
152163
} else {
153-
codePoints.push(charCode);
164+
encoded.push(charCode);
154165
}
155166
++i;
156167
}
157-
return codePoints;
168+
169+
encodedStringCache.set(string, encoded);
170+
171+
return encoded;
158172
}
159173

160174
export function printOperationsArray(operations: Array<number>) {

0 commit comments

Comments
 (0)