From 5b1a7c6b898a23d176ae5dc29016015832c40b1e Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Sat, 15 Sep 2018 12:39:31 +0800 Subject: [PATCH] perf(nodes-generator): 4x faster node generating refactored recurse to loop, time for processing 4000 items reduces from 6ms to 1.4ms --- src/utils/visibleNodesGenerator.js | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/utils/visibleNodesGenerator.js b/src/utils/visibleNodesGenerator.js index 3f0526c..36723e7 100644 --- a/src/utils/visibleNodesGenerator.js +++ b/src/utils/visibleNodesGenerator.js @@ -171,19 +171,26 @@ export default class VisibleNodesGenerator { this.focusedNode = null this.depths.clear() const nodesSet = new Set() // prevent duplication - const get = (nodes, depth = 0) => { - return [].concat( - ...nodes.map(node => { - if (nodesSet.has(node)) return [] - this.depths.set(node, depth) - nodesSet.add(node) - const children = this.expandedNodes.has(node) ? get(node.contents, depth + 1) : [] - return [node, ...children] - }) - ) + const nodes = [], stack = this.searchedNodes.slice().reverse() + let current, depth = 0 + while (stack.length) { + current = stack.pop() + if (current === null) { + depth -= 1 + continue + } + if (nodesSet.has(current)) continue + nodes.push(current) + nodesSet.add(current) + this.depths.set(current, depth) + if (this.expandedNodes.has(current)) { + stack.push(null) // use null as pop depth flag + stack.push(...current.contents.slice().reverse()) + depth += 1 + } } this.visibleNodes = { - nodes: get(this.searchedNodes), + nodes, depths: this.depths, expandedNodes: this.expandedNodes, }