Identical code slower than JS closure library equivalent

67 views Asked by At

I wanted to create a binary search algorithm with some modifications. So I grabbed the code from Google's closure library and started making these modifications. My modified version seemed slower than it should be so I slowly took out anything I thought could be affecting the speed. What I was left with is a SIMPLER version of the binary search algorithm and it was still several times slower in both Chrome or firefox. What could be causing this? Take a look at this test page. Inspect the source to see what I'm talking about.

https://dl.dropboxusercontent.com/s/4hhuq4biznv1jfd/SortedArrayTest.html

This is google's version.

goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
    opt_selfObj) {
  var left = 0;  // inclusive
  var right = arr.length;  // exclusive
  var found;
  while (left < right) {
    var middle = (left + right) >> 1;
    var compareResult;
    if (isEvaluator) {
      compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
    } else {
      compareResult = compareFn(opt_target, arr[middle]);
    }
    if (compareResult > 0) {
      left = middle + 1;
    } else {
      right = middle;
      // We are looking for the lowest index so we can't return immediately.
      found = !compareResult;
    }
  }
  // left is the index if found, or the insertion point otherwise.
  // ~left is a shorthand for -left - 1.
  return found ? left : ~left;
};

This is my version:

        var search = function(array, num){
            var left = 0;  // inclusive
            var right = array.length;  // exclusive
            while (left < right) {
                var middle = (left + right) >> 1;
                var midValue = array[midValue];
                if (num > midValue) {
                    left = middle + 1;
                } else {
                    right = middle;
                }
            }
            return left;
        };

Since people seem to think its something with the comparefn function...when you don't provide a comparer function to the binarySearch method it uses the following default compare function:

    goog.array.defaultCompare = function(a, b) {
      return a > b ? 1 : a < b ? -1 : 0;
    };

    goog.array.binarySearch = function(arr, target, opt_compareFn) {
  return goog.array.binarySearch_(arr,
      opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
      target);
};

Please don't respond without looking at the code. Guesses aren't very helpful.

1

There are 1 answers

1
sjrd On BEST ANSWER

Your implementation contains a bug. It contains:

var midValue = array[midValue]

which should be

var midValue = array[middle]

instead.

Apparently, your were unlucky enough for your data set not to expose the bug as an incorrect result, but just as a performance problem.