title: Performance: why is the first implementation of the same algorithm significantly faster
body: <p>The algorithm is taken from LeetCode: <a href="https://leetcode.com/problems/maximum-product-of-word-lengths/description/" rel="nofollow noreferrer">https://leetcode.com/problems/maximum-product-of-word-lengths/description/</a></p>
  
  <p>Here is the jsperf I created (I have some local tests which gives the same result): <a href="https://jsperf.com/maximum-product-of-word-lengths" rel="nofollow noreferrer">https://jsperf.com/maximum-product-of-word-lengths</a></p>
  
  <p>Here is the first "slow" implementation:</p>
  
  <pre><code>function maxProduct (words) {
      if (!words || !words.length) return 0;
      let len = words.length;
      let values = [];
      // console.log(values)
      for (let i = 0; i &lt; len; ++i) {
          let tmp = words[i];
          let num = 0, len = tmp.length;
          for (let j = 0; j &lt; len; ++j) {
              num |= 1 &lt;&lt; (tmp.charCodeAt(j) - 'a'.charCodeAt(0));
          }
          values[i] = {
              num: num,
              len: tmp.length
          };
      }
  
      let maxProduct = 0;
      for (let i = 0; i &lt; len; ++i) {
          for (let j = 0; j &lt; len; ++j) {
              if ((values[i].num &amp; values[j].num) == 0) {
                  maxProduct = Math.max(maxProduct, values[i].len * values[j].len);
              }
          }
      }
      return maxProduct;
    };
  </code></pre>
  
  <p>Here is the "fast" implementation:</p>
  
  <pre><code> function maxProductFast (words) {
        var temp = [];
        for(var i = 0; i &lt; words.length; i++){
            var tempObj = {};
            tempObj.item = words[i];
  
            var num = 0;
            for(var j = 0; j &lt; words[i].length; j++){
                num |= 1 &lt;&lt; (words[i].charCodeAt(j) - 97);
            }
  
            tempObj.num = num;
            temp.push(tempObj);
        }
  
        var res = 0;
  
        for(var i = 0; i &lt; temp.length; i++){
            for(var j = i + 1; j &lt; temp.length; j++){
                var item1 = temp[i];
                var item2 = temp[j];
  
                if((item1.num &amp; item2.num) == 0) {
                    res = Math.max(res, item1.item.length * item2.item.length);
                }
  
            }
        }
  
        return res;
    }
  </code></pre>