I was surprised when benchmarking the code that the recursive variant was faster than iterative approaches. Is there a flaw in my implementations (they each iterate the same number of elements to the same depth)? The snippets arearen't strictly equivalent in the order they touch the elements though I doubt that effects the performance.
function iterate(current, depth) {
var children = current.childNodes;
if (!children) return; //handle text nodes
for (var i = 0, len = children.length; i < len; i++) {
iterate(children[i], depth + 1);
}
}
iterate(parentElement, 0);
var stack = [{
depth: 0,
element: treeHeadNode
}];
var stackItem = 0;
var current;
var children, i, len;
var depth;
while (current = stack[stackItem++]) {
//get the arguments
depth = current.depth;
current = current.element;
children = current.childNodes;
for (i = 0, len = children.length; i < len; i++) {
stack.push({ //pass args via object or array
element: children[i],
depth: depth + 1
});
}
}
var stack = [{
depth: 0,
element: treeHeadNode
}];
var current;
var children, i, len;
var depth;
while (current = stack.pop()) {
//get the arguments
depth = current.depth;
current = current.element;
children = current.childNodes;
for (i = 0, len = children.length; i < len; i++) {
stack.push({ //pass args via object or array
element: children[i],
depth: depth + 1
});
}
}