JS startsWith (v16)

Revision 16 of this benchmark created on


Description

Perf-testing a JS startsWith() function

Preparation HTML

<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;
  }

  // Using firstIndexOf === 0
  var firstIndexChk = function(data, str) {
   return data.indexOf(str, 0) === 0;
  }  
  
  // sample data
  var origString = 'hello, world';
  var testString = 'he';
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
String.prototype.startsWith1
origString.startsWith1(testString);
ready
String.prototype.startsWith2
origString.startsWith2(testString);
ready
subStringChk
subStringChk(origString, testString);
ready
lastIndexChk
lastIndexChk(origString, testString);
ready
firstIndexChk
firstIndexChk(origString, testString);
ready

Revisions

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