I read an online book. It gave an callback pattern example as follow.
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());
It said that this is not efficient, for it loop through found nodes twice, and the following code is more efficient.
// 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);
However, both of them are O(n), and the overhead of calling a function may be large, which causes each iteration in findNodes() (with callback) takes more time. So I wonder if this modification really makes different as the author said. And how should I measure the cost of the two implements?
findNodesis going to return. If it is quite small then either approach will have pretty much the same performance. For very large it may be that the callback is better. However, as the "complex logic" is handled out byfindNodes(in the first example) then the further iteration shouldn't be too costly.