JS startsWith

JavaScript performance comparison

Test case created by Bob

Info

Perf-testing a JS startsWith() function

Preparation code

<script>
  // Methods to test
  // String.prototype.startsWith1 using ===
  if (!String.prototype.startsWith1) {
   String.prototype.startsWith1 = function(str) {
    return (this.indexOf(str) === 0);
   }
  }
 
  // String.prototype.startsWith using !
  if (!String.prototype.startsWith2) {
   String.prototype.startsWith2 = function(str) {
    return !this.indexOf(str);
   }
  }
 
  // Using substr
  var subStringChk = function(data, str) {
   return data.substr(0, str.length) === str;
  }
 
 
 
  // Using lastIndexOf === 0
  var lastIndexChk = function(data, str) {
   return data.lastIndexOf(str, 0) === 0;
  }
 
 
  // sample data
  var origString = 'hello, world';
  var testString = 'he';
</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
String.prototype.startsWith1
origString.startsWith1(testString);
pending…
String.prototype.startsWith2
origString.startsWith2(testString);
pending…
subStringChk
subStringChk(origString, testString);
pending…
lastIndexChk
lastIndexChk(origString, testString);
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