Slice vs Substr vs Substring vs [ ] Methods

JavaScript performance comparison

Revision 31 of this test case created

Info

This is comparing the runtimes of [ ], substr, substring, and slice in a string for large (66000 character) string size.

Preparation code

<script type="text/javascript">
  var longString = "";
  // Large = 66,000
  for (var i = 0; i < 66000; i++) {
    longString += i % 10;
  }
  var len = 10;
  var arr = longString.split('');
</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
Substring
for (i = 0; i < longString.length; i++) {
  longString.substring(i, i + len);
}
pending…
Slice
for (i = 0; i < longString.length; i++) {
  longString.slice(i, i + len);
}
pending…
Substr
for (i = 0; i < longString.length; i++) {
  longString.substr(i, len);
}
pending…
[ ] (array)
for (i = 0; i < longString.length; i++) {
  resultArray = new Array(len);
  for (j = 0; j < len; j++) {
    resultArray[j] = longString[i + j];
  }
  resultArray.join('');
}
pending…
charAt (array)
for (i = 0; i < longString.length; i++) {
  resultArray = new Array(len);
  for (j = 0; j < len; j++) {
    resultArray[j] = longString.charAt(i + j);
  }
  resultArray.join('');
}
pending…
[ ] (string)
for (i = 0; i < longString.length; i++) {
  result = '';
  for (j = 0; j < len; j++) {
    result += longString[i + j];
  }
}
pending…
charAt (string)
for (i = 0; i < longString.length; i++) {
  result = '';
  for (j = 0; j < len; j++) {
    result += longString.charAt(i + j);
  }
}
pending…
Array slice
for (i = 0; i < longString.length; i++) {
  arr.slice(i, i + len).join('');
}
pending…
Array to substr
for (i = 0; i < longString.length; i++) {
  var idx = 0;

  for (j = 0; j < len; j++) {
    idx += (arr[i + j] || '').length;
  }

  longString.substr(i, idx);
}
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