String split by length

JavaScript performance comparison

Revision 3 of this test case created by gildas

Preparation code

<script type="text/javascript">

splitRegex = function(str, len) {
  var regex = new RegExp('[\\s\\S]{1,' + len + '}', 'g');
  return str.match(regex);
}

var splitRegexCached = (function(){
  var regexCache = {};
  return( function(str, len) {
    var regex = regexCache[len] || (regexCache[len] = new RegExp('[\\s\\S]{1,' + len + '}', 'g'));
    return str.match(regex);
  });
})();

function splitSlice(str, len) {
  var ret = [ ];
  for (var offset = 0, strLen = str.length; offset < strLen; offset += len) {
    ret.push(str.slice(offset, len + offset));
  }
  return ret;
}

function splitSubstr(str, len) {
  var ret = [ ];
  for (var offset = 0, strLen = str.length; offset < strLen; offset += len) {
    ret.push(str.substr(offset, len));
  }
  return ret;
}

function splitSubstring(str, len) {
  var ret = [ ];
  for (var offset = 0, strLen = str.length; offset < strLen; offset += len) {
    ret.push(str.substring(offset, offset + len));
  }
  return ret;
}

var tinyString  = (new Array(39)).join('abcdefghijklmnopqrstuvwxyz');
var shortString  = (new Array(385)).join('abcdefghijklmnopqrstuvwxyz');
var mediumString  = (new Array(3856)).join('abcdefghijklmnopqrstuvwxyz');
var longString  = (new Array(38462)).join('abcdefghijklmnopqrstuvwxyz');
var spanArray = [6666, 2, 3339, 5, 1620, 13, 847, 22, 521, 46,  254, 88, 145];
var spanLength = spanArray.length;
var i = 0, span;
</script>
<script>
Benchmark.prototype.teardown = function() {
    i = 0;
};
</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
Regex
span = spanArray[i++ % spanLength];
splitRegex(tinyString, span);
splitRegex(shortString, span);
splitRegex(mediumString, span);
splitRegex(longString, span);
pending…
Regex (Cached)
span = spanArray[i++ % spanLength];
splitRegexCached(tinyString, span);
splitRegexCached(shortString, span);
splitRegexCached(mediumString, span);
splitRegexCached(longString, span);
 
pending…
string.Substr
span = spanArray[i++ % spanLength];
splitSubstr(tinyString, span);
splitSubstr(shortString, span);
splitSubstr(mediumString, span);
splitSubstr(longString, span);
pending…
string.Slice
span = spanArray[i++ % spanLength];
splitSlice(tinyString, span);
splitSlice(shortString, span);
splitSlice(mediumString, span);
splitSlice(longString, span);
pending…
string.substring
span = spanArray[i++ % spanLength];
splitSubstring(tinyString, span);
splitSubstring(shortString, span);
splitSubstring(mediumString, span);
splitSubstring(longString, span);
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