title: A Javascript callback pattern example - is it really more efficient?
body: <p>I read an online <a href="http://my.safaribooksonline.com/book/programming/javascript/9781449399115/functions/callback_pattern#X2ludGVybmFsX0ZsYXNoUmVhZGVyP3htbGlkPTk3ODE0NDkzOTkxMTUvYmFja2dyb3VuZA==" rel="nofollow">book</a>. It gave an callback pattern example as follow.</p>
  
  <pre><code>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 &lt; max; i += 1) {
          nodes[i].style.display = "none";
      }
  };
  
  // executing the functions
  hide(findNodes());
  </code></pre>
  
  <p>It said that this is not efficient, for it loop through found nodes twice, and the following code is more efficient.</p>
  
  <pre><code>// 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);
  </code></pre>
  
  <p>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?</p>