slice vs. substr vs. substring vs. split vs. RegExp

JavaScript performance comparison

Revision 13 of this test case created

Info

Comparing different ways to extract text from a string.

Preparation code

<script>
  var str = 'blahblahblah_123456789';
  var part1;
  var part2;
  var opt;
  var MRE = /[^_]/g;
  var ERE = /(.*)_(.*)/;
  var SRE = /_/g;
</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
slice
// Get first part ("blahblahblah")
part1 = str.slice(0, str.indexOf('_'));

// Get second part ("123456789")
part2 = str.slice(str.indexOf('_') + 1);
pending…
substr
// Get first part ("blahblahblah")
part1 = str.substr(0, str.indexOf('_'));

// Get second part ("123456789")
part2 = str.substr(str.indexOf('_') + 1);
pending…
substring
// Get first part ("blahblahblah")
part1 = str.substring(0, str.indexOf('_'));

// Get second part ("123456789")
part2 = str.substring(str.indexOf('_') + 1);
pending…
split
// Get first part ("blahblahblah")
var aray = str.split('_');
part1 = aray[0];
part2 = aray[1];
pending…
String match
// Get first part ("blahblahblah")
var aray = str.match(MRE);
part1 = aray[0];
part2 = aray[1];
pending…
String Replace
// Get first part ("blahblahblah")
part1 = str.replace(/_.+$/, '');

// Get second part ("123456789")
part2 = str.replace(/^.+_/, '');
pending…
Substring 1 indexOf
// Get first part ("blahblahblah")
part1 = str.substr(0, opt = str.indexOf('_'));

// Get second part ("123456789")
part2 = str.substr(opt + 1);
pending…
Slice 1 indexOf
// Get first part ("blahblahblah")
part1 = str.slice(0, opt = str.indexOf('_'));

// Get second part ("123456789")
part2 = str.slice(opt + 1);
pending…
split limited
// Get first part ("blahblahblah")
var aray = str.split('_', 2);
part1 = aray[0];
part2 = aray[1];
pending…
RegExp exec
// for completeness...
var aray = ERE.exec(ERE);
part1 = aray[1];
part2 = aray[2];
pending…
split RE
var aray = str.split(SRE);
part1 = aray[0];
part2 = aray[1];
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