startsWith speed comparison

JavaScript performance comparison

Revision 63 of this test case created by José Raupp da Rosa Junior

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.0.0/underscore.string.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  a = ["test"];
  for (var i = 0; i < 10000; i++) {
    a.push("some other stuff");
  }
  str = a.join();
  
  String.prototype.startsWith = function(needle) {
  	return this.slice(0, needle.length) === needle;
  };
  
  String.prototype.startsWithLoop = function(needle) {
    var that = this;
  	var ceil = needle.length;
  	for(var i = 0; i < ceil; i++) {
  		if(that[i] !== needle[i]) return false;
  	}
  	return true;
  }
  
  function startsWith(haystack, needle) {
  	return haystack.slice(0, needle.length) === needle;
  }
  
  function startsWithLoop(haystack, needle) {
  	var ceil = needle.length;
  	for(var i = 0; i < ceil; i++) {
  		if(haystack[i] !== needle[i]) return false;
  	}
  	return true;
  }

};
</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
lastIndexOf
r1 = (str.lastIndexOf("test", 0) === 0);
r2 = (str.lastIndexOf("not there", 0) === 0);
pending…
slice
r1 = (str.slice(0, 4) === "test");
r2 = (str.slice(0, 9) === "not there");
pending…
indexOf
r1 = (str.indexOf("test",0) === 0);
r2 = (str.indexOf("not there",0) === 0);
pending…
startsWithLoop
r1 = startsWithLoop(str, 'test');
r2 = startsWithLoop(str, 'not there');
pending…
Proto startsWithLoop
r1 = str.startsWithLoop('test');
r2 = str.startsWithLoop('not there');
pending…
Includes
r1 = str.includes('test');
r2 = str.includes('not there');
pending…
regex
r1 = (/^test/).test(str);
r2 = (/^not there/).test(str);
pending…
Underscore startsWith
r1 = s.startsWith(str, 'test');
r2 = s.startsWith(str, 'not there');
pending…
substring
r1 = (str.substring(0, 4) === "test");
r2 = (str.substring(0, 9) === "not there");
pending…
Proto startsWith
r1 = str.startsWith('test');
r2 = str.startsWith('not there');
pending…
startsWith
r1 = startsWith(str, 'test');
r2 = startsWith(str, 'not there');
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.

0 Comments