Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 OPR/80.0.4170.61
Opera 80
Windows
Desktop
3 years ago
Test name Executions per second
Set With For Loop 0.3 Ops/sec
Sort With For Loop 387.0 Ops/sec
Sort With Reduce 141.4 Ops/sec
Script Preparation code:
AخA
 
var array = [];
array.length = 10000;
array.fill(undefined);
array = array.map(() => Math.floor(Math.random() * array.length));
Tests:
  • Set With For Loop

    x
     
    const set = new Set(array);
    const maxSetValue = array.reduce(Math.max);
    function findSet() {
      for (let i = 0; i < maxSetValue; i++) 
        if (!set.has(i)) return i;
      return -1;
    }
    findSet();
  • Sort With For Loop

     
    const sortedArray = array.slice().sort((a, b) => a - b);
    const maxSortValue = sortedArray[array.length - 1];
    function findSort() {
        for (let i = 0; i < maxSortValue; i++)
          if (!sortedArray.includes(i)) return i;
      
      return -1;
    }
    findSort();
  • Sort With Reduce

     
    const sortedReduceArray = array.slice().sort((a, b) => a - b);
    function findReduce() {
        return sortedReduceArray.reduce((acc, current) => (Math.abs(current - acc) > 1 ? Math.min : Math.max)(current, acc), 0) + 1;
    }
    findReduce();