オンラインの本を読みました。コールバックパターンの例を次のように示しました。
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());
見つかったノードを2回ループするため、これは効率的ではないと言われています。次のコードの方が効率的です。
// 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()(コールバックを使用)の各反復に時間がかかります。ですから、作者が言ったように、この変更は本当に違うのだろうかと思います。そして、2つの道具のコストをどのように測定する必要がありますか?