localeCompare

JavaScript performance comparison

Revision 3 of this test case created by Jonathon Hibbard

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var rawData = ["yeah", "this is", "a", "wonderful", "blue", "world", "But", "its", "poisoned", "with", "hate", "and", "apathy" ];
   
    var sortedStrings = [];
    for (i = 0; i < 1000; i++) {
      sortedStrings.push(rawData[Math.random()*(rawData.length-1) | 0]);
    }
   
    sortedStrings.sort();
};

Benchmark.prototype.teardown = function() {
    unSortedStrings = [];
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
localeCompare
function binaryIndexOf(array, searchElement) {
  'use strict';

  var minIndex = 0;
  var maxIndex = array.length - 1;
  var currentIndex;
  var currentElement;

  while (minIndex <= maxIndex) {
      currentIndex = (minIndex + maxIndex) / 2 | 0;
      currentElement = array[currentIndex];

      var comparison = currentElement.localeCompare(searchElement);
      if (comparison < 0) {
          minIndex = currentIndex + 1;
      }
      else if (comparison > 0) {
          maxIndex = currentIndex - 1;
      }
      else {
          return currentIndex;
      }
  }

  return -1;
}

binaryIndexOf(sortedStrings, "wonderful");
pending…
Custom
function simpleCompare(s1, s2) { s1 < s2 ? -1 : s1 > s2 ? 1 : 0;}

function binaryIndexOf(array, searchElement) {
  'use strict';

  var minIndex = 0;
  var maxIndex = array.length - 1;
  var currentIndex;
  var currentElement;

  while (minIndex <= maxIndex) {
      currentIndex = (minIndex + maxIndex) / 2 | 0;
      currentElement = array[currentIndex];

      var comparison = simpleCompare(currentElement, searchElement);
      if (comparison < 0) {
          minIndex = currentIndex + 1;
      }
      else if (comparison > 0) {
          maxIndex = currentIndex - 1;
      }
      else {
          return currentIndex;
      }
  }

  return -1;
}

binaryIndexOf(sortedStrings, "wonderful");
pending…
bTreeSearch
var bTreeSearch = function(n, h) {
  var mn = 0, mx = h.length - 1, r, z;
  do {
    r = ((mn+mx) >> 1);
    z = h[r];
    if(z == n) return r;
    if(z < n) mn = r; else mx = r;
  } while(true);
  return -1;
}

bTreeSearch("wonderful", sortedStrings)
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. Here’s a list of current revisions for this page:

1 comment

Jonathon Hibbard (revision owner) commented :

FYI, the Custom test is returning the incorrect result

Add a comment