Skip to content

Commit ae4e83b

Browse files
perf: Speed up JSON size calculation (#3348)
Alters `getJsonSizeUnsafe` to not use `TextEncoder` as this has proven slow on mobile. We don't need full byte length accuracy for the uses of `getJsonSizeUnsafe` anyway, so this is an OK tradeoff for performance. --------- Co-authored-by: Maarten Zuidhoorn <[email protected]>
1 parent b8792af commit ae4e83b

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

packages/snaps-utils/src/json.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,14 @@ export function parseJson<Type extends Json = Json>(json: string) {
2323
*
2424
* This may sometimes be preferred over `getJsonSize` for performance reasons.
2525
*
26+
* Note: This function does not encode the string to bytes, thus the input may
27+
* be about 4x larger in practice. Use this function with caution.
28+
*
2629
* @param value - The JSON value to get the size of.
2730
* @returns The size of the JSON value in bytes.
2831
*/
2932
export function getJsonSizeUnsafe(value: Json): number {
3033
const json = JSON.stringify(value);
31-
return new TextEncoder().encode(json).byteLength;
34+
// We intentionally don't use `TextEncoder` because of bad performance on React Native.
35+
return json.length;
3236
}

0 commit comments

Comments
 (0)