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

JavaScript performance comparison

Test case created by Tom Doan

Info

Comparing different ways to extract text from a string.

Preparation code

<script>
  var str = 'blahblahblah_123456789';
</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")
str.slice(0, str.indexOf('_'));

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

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

// Get second part ("123456789")
str.substring(str.indexOf('_') + 1);
pending…
split
// Get first part ("blahblahblah")
str.split('_')[0];

// Get second part ("123456789")
str.split('_')[1];
pending…
RegExp
// Get first part ("blahblahblah")
str.replace(/_.+$/, '');

// Get second part ("123456789")
str.replace(/^.+_/, '');
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