The library for web and native user interfaces.
Make ReactMount.findComponentRoot breadth-first & non-recursive.
This function needs to be as fast as possible for those cases when `ReactID.getNode` can't rely on the `nodeCache`. Breadth-first search prevents us from diving too deeply down the wrong branches when the sought-after node can be found at a shallower level. The queue required for breadth-first search is implemented by a single array indexed by `childIndex`. To save space, only the `.firstChild` nodes are stored, and we use `.nextSibling` to iterate over the other siblings in a `while` loop.
Ben Newman committed
Jul 8, 2013 at 11:48 UTC
a5ddb07cb3d390cde3d294533cc1aaac763f0b48
1 file changed
+21
-9
src/core/ReactInstanceHandles.js
+21
-9
@@ -284,18 +284,30 @@ var ReactInstanceHandles = {
284
* @internal
285
*/
286
findComponentRoot: function(ancestorNode, id) {
287
- var child = ancestorNode.firstChild;
288
- while (child) {
289
- var childID = ReactID.getID(child);
290
- if (childID) {
291
- if (id === childID) {
292
- return child;
293
- } else if (isAncestorIDOf(childID, id)) {
294
- return ReactInstanceHandles.findComponentRoot(child, id);
287
+ var firstChildren = [ancestorNode.firstChild];
288
+ var childIndex = 0;
289
+
290
+ while (childIndex < firstChildren.length) {
291
+ var child = firstChildren[childIndex++];
292
+ while (child) {
293
+ var childID = ReactID.getID(child);
294
+ if (childID) {
295
+ if (id === childID) {
296
+ return child;
297
+ } else if (isAncestorIDOf(childID, id)) {
298
+ // If we find a child whose ID is an ancestor of the given ID,
299
+ // then we can be sure that we only want to search the subtree
300
+ // rooted at this child, so we can throw out the rest of the
301
+ // search state.
302
+ firstChildren.length = childIndex = 0;
303
+ firstChildren.push(child.firstChild);
304
+ break;
305
+ }
306
}
307
+ child = child.nextSibling;
308
}
297
- child = child.nextSibling;
309
}
310
+
311
global.console && console.error && console.error(
312
'Error while invoking `findComponentRoot` with the following ' +
313
'ancestor node:',