indexOf vs substring

JavaScript performance comparison

Test case created by Shane O'Sullivan

Info

tests whether it is faster to check indexOf at the end of a string rather than getting the substring

Preparation code

<script>
  var str = "abcdefghijklmnopqrstuvwxyz.css";
  var str2 = "ab";
  var str3 = ".cssojdvjsdscscd"
 
  var needle1 = ".css";
  var needle2 = "qwertyuiopasdfghjklzxcvbnm";
</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
indexOf
str.indexOf(needle1) == str.length - needle1.length;
str2.indexOf(needle1) == str2.length - needle1.length;
str3.indexOf(needle1) == str3.length - needle1.length;

str.indexOf(needle2) == str.length - needle2.length;
str2.indexOf(needle2) == str2.length - needle2.length;
str3.indexOf(needle2) == str3.length - needle2.length;
 
pending…
substring
str.substring(str.length - needle1.length) === needle1;
str2.substring(str2.length - needle1.length) === needle1;
str3.substring(str3.length - needle1.length) === needle1;

str.substring(str.length - needle2.length) === needle2;
str2.substring(str2.length - needle2.length) === needle2;
str3.substring(str3.length - needle2.length) === needle2;
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