localeCompare

JavaScript performance comparison

Revision 2 of this test case created by hrj

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 < s1 ? -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…

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:

0 comments

Add a comment