我在線閱讀book。它給出了一個回調模式的例子如下。一個Javascript回調模式的例子 - 它真的更有效嗎?
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每次迭代()(與回調)需要更多的時間。所以我想知道這個修改是否真的與作者所說的不同。我該如何衡量這兩種工具的成本?
這將取決於某些部分平均有多少節點'findNodes'要返回。如果它很小,那麼兩種方法的性能都差不多。對於非常大的回調可能會更好。然而,由於「複雜邏輯」是由'findNodes'處理的(在第一個例子中),那麼進一步的迭代不應該太昂貴。 –
http://jsperf.com/normal-vs-callback – Christoph