Skip to content

Commit 5c81dd5

Browse files
author
Lotus Dev
committed
perf: apply PR WhiskeySockets#2093 - cache binary nodes for 10x-30x faster processing
1 parent 3f4ba52 commit 5c81dd5

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

src/WABinary/generic-utils.ts

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,32 @@ import { type BinaryNode } from './types'
44

55
// some extra useful utilities
66

7+
const indexCache = new WeakMap<BinaryNode, Map<string, BinaryNode[]>>()
8+
79
export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: string) => {
8-
if (Array.isArray(node?.content)) {
9-
return node.content.filter(item => item.tag === childTag)
10+
if (!node || !Array.isArray(node.content)) return []
11+
12+
let index = indexCache.get(node)
13+
14+
// Build the index once per node
15+
if (!index) {
16+
index = new Map<string, BinaryNode[]>()
17+
18+
for (const child of node.content) {
19+
let arr = index.get(child.tag)
20+
if (!arr) index.set(child.tag, (arr = []))
21+
arr.push(child)
22+
}
23+
24+
indexCache.set(node, index)
1025
}
1126

12-
return []
27+
// Return first matching child
28+
return index.get(childTag) || []
29+
}
30+
31+
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
32+
return getBinaryNodeChildren(node, childTag)[0]
1333
}
1434

1535
export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
@@ -20,12 +40,6 @@ export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
2040
return []
2141
}
2242

23-
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
24-
if (Array.isArray(node?.content)) {
25-
return node?.content.find(item => item.tag === childTag)
26-
}
27-
}
28-
2943
export const getBinaryNodeChildBuffer = (node: BinaryNode | undefined, childTag: string) => {
3044
const child = getBinaryNodeChild(node, childTag)?.content
3145
if (Buffer.isBuffer(child) || child instanceof Uint8Array) {

0 commit comments

Comments
 (0)