4 simple loops vs Lo-Dash`, and a simple loop

JavaScript performance comparison

Revision 29 of this test case created by tomByrer

Info

v29: from v28, removed reverse, micro-optimized Simpler Halved test, copy+paste array (now doubled)

Preparation code

</script>
<script src="//cdn.jsdelivr.net/lodash/2.4.1/lodash.min.js">
</script>
<script>
  var lodash = _.noConflict();
</script>
<script>
Benchmark.prototype.setup = function() {
    var r, lodash = window.lodash;
   
    function contains(array, value) {
      var index = -1,
          length = array.length;
   
      while (++index < length) {
        if (array[index] === value) {
          return true;
        }
      }
      return false;
    }
   
    function contains2(array, value) {
      for (var i = 0, m = array.length; i < m; i++) {
        if (array[i] === value) {
          return true;
        }
      }
      return false;
    }
   
    function contains3(array, value) {
      for (var i = 0, l = array.length - 1, m=Math.floor(l/2); i <= m; i++) {
        if (array[i] === value) return true;
        else if (array[(l-i)] === value) return true;    
      }
      return false;
    }
   
    function contains4(array, value) {
      var l = array.length - 1;
      var n = l*0.5;
      var m = n>0?~~n:n==~~n?n:~~n-1;  //math.floor()
      for (var i = 0; i <= m; i++) {
        if (array[i] === value) return true;
        else if (array[(l-i)] === value) return true;    
      }
      return false;
    }
   
    var array = [321, 182, 976, 413, 382, 697, 996, 629, 233, 412, 211, 424,
    609,
    965, 925, 560, 386, 807, 140, 952, 904, 833, 586, 139, 466, 226, 687, 119, 363, 784, 24, 792, 352, 376, 375, 606, 508, 716, 114, 291, 237, 544, 891, 518, 440, 395, 449, 841, 699, 284, 936, 818, 840, 162, 93];
   
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Simple Loop
r = contains(array, 609);
pending…
Simpler Loop
r = contains2(array, 609);
pending…
Simpler halved
r = contains3(array, 609);
pending…
Simpler Halved3
r = contains4(array, 609);
pending…
lodash.indexOf
r = lodash.indexOf(array, 609) > -1;
pending…
lodash.contains
r = lodash.contains(array, 609);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

tomByrer (revision owner) commented :

My note above about the array is wrong; it is actually much smaller.

Add a comment