Skip to content

Commit

Permalink
perf: reduce linear search on list traversing
Browse files Browse the repository at this point in the history
  • Loading branch information
JLHwung committed Nov 3, 2020
1 parent 487f82e commit 04cba55
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 18 deletions.
7 changes: 4 additions & 3 deletions packages/babel-traverse/src/context.js
Expand Up @@ -95,7 +95,7 @@ export default class TraversalContext {
this.queue = queue;
this.priorityQueue = [];

const visited = [];
const visited = new WeakSet();
let stop = false;

// visit the queue
Expand All @@ -120,8 +120,9 @@ export default class TraversalContext {
}

// ensure we don't visit the same node twice
if (visited.indexOf(path.node) >= 0) continue;
visited.push(path.node);
const { node } = path;
if (visited.has(node)) continue;
if (node) visited.add(node);

if (path.visit()) {
stop = true;
Expand Down
18 changes: 5 additions & 13 deletions packages/babel-traverse/src/path/index.js
Expand Up @@ -67,24 +67,16 @@ export default class NodePath {

const targetNode = container[key];

const paths = pathCache.get(parent) || [];
if (!pathCache.has(parent)) {
let paths = pathCache.get(parent);
if (!paths) {
paths = new Map();
pathCache.set(parent, paths);
}

let path;

for (let i = 0; i < paths.length; i++) {
const pathCheck = paths[i];
if (pathCheck.node === targetNode) {
path = pathCheck;
break;
}
}

let path = paths.get(targetNode);
if (!path) {
path = new NodePath(hub, parent);
paths.push(path);
if (targetNode) paths.set(targetNode, path);
}

path.setup(parentPath, container, listKey, key);
Expand Down
3 changes: 1 addition & 2 deletions packages/babel-traverse/src/path/modification.js
Expand Up @@ -163,8 +163,7 @@ export function updateSiblingKeys(fromIndex, incrementBy) {
if (!this.parent) return;

const paths = pathCache.get(this.parent);
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
for (const [, path] of paths) {
if (path.key >= fromIndex) {
path.key += incrementBy;
}
Expand Down

0 comments on commit 04cba55

Please sign in to comment.