我读了一本在线书。它给出了一个回调模式示例,如下所示。
var findNodes = function () {
var i = 100000, // big, heavy loop
nodes = [], // stores the result
found; // the next node found
while (i) {
i -= 1;
// complex logic here...
nodes.push(found);
}
return nodes;
};
var hide = function (nodes) {
var i = 0, max = nodes.length;
for (; i < max; i += 1) {
nodes[i].style.display = "none";
}
};
// executing the functions
hide(findNodes());
它说这效率不高,因为它循环两次找到的节点,下面的代码效率更高。
// refactored findNodes() to accept a callback
var findNodes = function (callback) {
var i = 100000,
nodes = [],
found;
// check if callback is callable
if (typeof callback !== "function") {
callback = false;
}
while (i) {
i -= 1;
// complex logic here...
// now callback:
if (callback) {
callback(found);
}
nodes.push(found);
}
return nodes;
};
// a callback function
var hide = function (node) {
node.style.display = "none";
};
// find the nodes and hide them as you go
findNodes(hide);
但是,两者都是O(n),调用函数的开销可能很大,导致findNodes()(带回调)的每次迭代都需要更多的时间。所以我想知道这个修改是否真的像作者所说的那样与众不同。我应该如何衡量这两种工具的成本?