Careful with that indexOf, Eugene

Benchmark created by Erik Corry on


Description

Using indexOf to determine whether a string starts or ends with another string is not going to work well.

Preparation HTML

<script>
  String.prototype.StartsWith = function(needle) {
   var len = needle.length;
   if (len > this.length) return false;
   for (var i = 0; i < len; i++) {
    if (needle.charCodeAt(i) !== this.charCodeAt(i)) return false;
   }
   return true;
  }
  
  String.prototype.EndsWith = function(needle) {
   var len = needle.length;
   if (len > this.length) return false;
   var offset = this.length - len;
   for (var i = 0; i < len; i++) {
    if (needle.charCodeAt(i) !== this.charCodeAt(offset + i)) return false;
   }
   return true;
  }
  
  
  
  var hayStack = "Now is the time for all good men to come to the aid of the party";
  hayStack += hayStack; // 128
  hayStack += hayStack; // 256
  hayStack += hayStack; // 512
  hayStack += hayStack; // 1024
  hayStack += hayStack; // 2048
  hayStack += hayStack; // 4096
  hayStack += hayStack; // 8192
  hayStack += hayStack; // 16384
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using indexOf
function use_index_of() {
 return hayStack.indexOf("fish") == 0;
}

use_index_of();
ready
Using StartsWith
function use_starts_with() {
 return hayStack.StartsWith("fish");
}

use_starts_with();
ready
Using regexp
var re = /^fish/;

function use_regexp() {
 re.test("foo"); // Defeat regexp cache!
 return re.test(hayStack);
}

use_regexp();
ready
Using lastIndexOf
function use_last_index_of() {
 return hayStack.lastIndexOf("fish") == hayStack.length - 4;
}

use_last_index_of();
ready
Using EndsWith
function use_ends_with() {
 return hayStack.EndsWith("fish");
}

use_ends_with();
ready
Last index using regexp no cache
var re2 = /fish$/;

function use_regexp2() {
 re2.test("foo"); // Defeat regexp cache!
 return re2.test(hayStack);
}

use_regexp2();
ready
Last index using regexp with caching
var re2 = /fish$/;

function use_regexp3() {
 return re2.test(hayStack);
}

use_regexp3();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.