Traversing a string - many substr() versus array conversion (v2)

Revision 2 of this benchmark created on


Description

What is faster when traversing each character of a string: doing a substr() or charAt() in every iteration, or converting the string to an array and back to a string?

Preparation HTML

<script>
  var example = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi egestas venenatis risus nec dictum. Quisque hendrerit tellus sed ante tincidunt dapibus. Morbi semper tristique massa sed placerat. In pellentesque felis non nibh facilisis porttitor. Nullam hendrerit pharetra tortor quis luctus.";
  var letters = { from: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", to: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("") };
  var translate = function(ch) {
    var index = letters.from.indexOf(ch);
    if (index >= 0) {
      return letters.to[index];
    }
    return ch;
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
substr() in each iteration
var temp = example;
for (var i = 0; i < temp.length; i++) {
  var ch = temp.substr(i, 1);
  ch = translate(ch);
  temp = temp.substr(0, i) + ch + temp.substr(i + 1);
}
ready
charAt() in each iteration
var temp = example;
for (var i = 0; i < temp.length; i++) {
  var ch = temp.charAt(i);
  ch = translate(ch);
  temp = temp.substr(0, i) + ch + temp.substr(i + 1);
}
ready
Convert to array and back
var temp = example.split("");
for (var i = 0; i < temp.length; i++) {
  var ch = temp[i];
  ch = translate(ch);
  temp[i] = ch;
}
temp = temp.join("");
ready
substr() in each iteration, with concatenation
var temp = example, result = "";
for (var i = 0; i < temp.length; i++) {
  var ch = temp.substr(i, 1);
  ch = translate(ch);
  result += ch;
}
ready
Convert to array and back, with push
var temp = example.split(""), result = [];
for (var i = 0; i < temp.length; i++) {
  var ch = temp[i];
  ch = translate(ch);
  result.push(ch);
}
result = result.join("");
ready
Array access (for those browsers that support it)
var temp = example;
for (var i = 0; i < temp.length; i++) {
  var ch = temp[i];
  ch = translate(ch);
  temp = temp.substr(0, i) + ch + temp.substr(i + 1);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.