String split by length

JavaScript performance comparison

Test case created by James Brumond

Preparation code


function splitRegex(str, len) {
  var regex = new RegExp('.{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;

var shortString  = 'abcdefg';
var longString   = (new Array(500)).join('qwertyuiopasdfghjklzxcvbnm');


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 w/ Short String
splitRegex(shortString, 2);
Regex w/ Long String
splitRegex(longString, 2);
Slice w/ Short String
splitSlice(shortString, 2);
Slice w/ Long String
splitSlice(longString, 2);

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment