title: binary search in typescript vs indexOf - how to get performance properly
body: <p>I wrote wrote binary search algorithm with some typescript and i wanted to get its performance against array.indexOf. My result show that typescript version is slower. I tried to measure performance in available benchmarks on web and they show that binary search is much faster (as it should be). Whats wrong with this code / typescript / the way im trying to get performance of functions? </p>
  
  <p>I tried benchmarks and results look completely different. <a href="http://jsben.ch/VBjt0" rel="nofollow noreferrer">http://jsben.ch/VBjt0</a></p>
  
  <p>My code below.</p>
  
  <pre><code>function binarySearch(
    sortedArray: number[],
    seekElement: number,
  ): number {
    let startIndex = 0;
    let endIndex: number = sortedArray.length - 1;
    while (startIndex &lt;= endIndex) {
      const mid = startIndex + Math.floor((endIndex - startIndex) / 2);
      const guess = sortedArray[mid];
      if (guess === seekElement) {
        return mid;
      } else if (guess &gt; seekElement) {
        endIndex = mid - 1;
      } else {
        startIndex = mid + 1;
      }
    }
  
    return -1;
  }
  
  const indexOfSearch = function(arr, element) {
    return arr.indexOf(element);
  };
  
  const testArray = [...Array(100000).keys()].map(x =&gt; x + 1);
  
  
  console.time('binarySearch');
  binarySearch(testArray, 4400) // binarySearch: 0.134ms
  console.timeEnd('binarySearch');
  
  console.time('indexOfSearch');
  indexOfSearch(testArray, 4400) // indexOfSearch: 0.029ms
  console.timeEnd('indexOfSearch');
  </code></pre>
  
  <p>I also tried to use <code>performance.now</code> with this util function:</p>
  
  <pre><code>import { performance } from 'perf_hooks';
  
  export const getPerformance = (func: Function, ...params) =&gt; {
    const start = performance.now();
  
    func(params);
  
    const end = performance.now();
  
    console.log(`${func.name} took ${end - start} milliseconds to execute`);
  }
  </code></pre>
  
  <p>but results are even worse. With the same testing array binary search using <code>getPerformance</code> function took 11ms while indexOf took 0.003ms. Its weird and i don't know what im doing wrong. Thanks for any help</p>