Where Do I Belong

JavaScript performance comparison

Test case created by worldclassdev

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // ITERATING AND COMPARING WITH A FORLOOP(BY FINDING THE IMMEDIATE LARGER VALUE)
  
  function whereIBelongForLoopLarger(arr, num) {
      arr.sort((a, b) => {
          return a - b
      })
  
      for (var i = 0; i < arr.length; i++) {
          if (arr[i] >= num) {
              return i
          }
      }
  
      return arr.length
  
  }
  
  // ITERATING AND COMPARING WITH A FORLOOP(BY COUNTING ALL SMALLER VALUES)
  
  function whereIBelongForLoopSmaller(arr, num) {
  
      var counter = 0
      for (i = 0; i < arr.length; i++) {
          if (num > arr[i]) {
              counter++
          }
      } 
  
      return counter
  }
  
  
  // USING A WHILE LOOP
  
  function whereIBelongWhile(arr, num) {
      arr.sort((a, b) => {
          return a - b
      })
  
      let counter = 0;
      while (num > arr[counter]) {
          counter++
      }
  
      return counter
  }
  
  
  // FINDING THE NUMBER'S INDEX IN THE ARRAY
  
  function whereIBelongIndexOf(arr, num) {
      arr.push(num)
  
      arr.sort((a, b) => a - b)
  
      return arr.indexOf(num)
  
  }

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Forloop(find larger value)
whereIBelongForLoopLarger([10, 20, 30, 40, 50], 30)
pending…
Forloop(count smaller values)
whereIBelongForLoopSmaller([10, 20, 30, 40, 50], 30)
pending…
While Loop
whereIBelongWhile([10, 20, 30, 40, 50], 30)
pending…
IndexOf Method
whereIBelongIndexOf([10, 20, 30, 40, 50], 30)
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.

0 Comments