Array.indexOf vs Set.has

JavaScript performance comparison

Test case created by teramako

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function Items () { this.list = []; }
    Items.prototype.has = function(item) {
      return this.list.indexOf(item) !== -1;
    };
    function Items2 () { this.set = new Set(); }
    Items2.prototype.has = function(item){
      return this.set.has(item);
    };
    var list = [];
    var items  = new Items();
    var items2 = new Items2();
   
   
    for (var i = 0; i < 1000; ++i) {
      var obj = {pos: i};
      list.push(obj);
      items.list.push(obj);
      items2.set.add(obj);
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
array.indexOf
var o = list[~~(Math.random() * 1000)];
items.has(o);
pending…
set.has
var o = list[~~(Math.random() * 1000)];
items2.has(o);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment