binary search vs loop

JavaScript performance comparison

Test case created by Jason

Preparation code

<script>
  for (var i = 0, searchArr = []; i < 2000; i++) {
   searchArr[i] = i;
  }
  
  var count = 0,
      curVal = 0;
</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
brute force
var num = Math.random() * 2000;

for (var i = 0; i < 2000; i++) {
 curVal = searchArr[i];
 if (curVal === num) {
  break;
 }
}
pending…
binary
var num = Math.random() * 2000;

while (num !== curVal) {
 curVal = searchArr[Math.round(searchArr.length / 2)];
 if (searchArr.length > 1) {
  if (curVal > num) {
   searchArr = searchArr.splice(0, searchArr.length / 2);
  } else if (curVal < num) {
   searchArr = searchArr.splice(Math.round(searchArr.length / 2), Math.round(searchArr.length / 2));
  }
 } else {
  curval = searchArr[0];
  break;
 }
}
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.

1 Comment

Mike commented :

Your binary search will only work on an ordered list correct?