Reverse string

JavaScript performance comparison

Revision 11 of this test case created

Preparation code

<script>
  var s = 'abcdefghijklmnopqrstuvwxyz';
  var str;
  var a = [];
  for(var i=0; i<100; i++)
       a.push(s);
  str=a.join("");
 
  function str_reverse1(str) {
   return str.split('').reverse().join('');
  }
 
  function str_reverse2(str) {
   var result = '',
       length = str.length;
   while (length--) {
    result += str[length];
   }
   return result;
  }
 
  function str_reverse3(str) {
   var result = [],
       length = str.length,
       pad = length;
   while (length--) {
    result[pad - length] = str[length];
   }
   return result.join('');
  }
 
  function str_reverse4(str) {
   var curr, result = str.split('');
   for (var i = 0, j = result.length - 1; i < j; i++, j--) {
    curr = result[i];
    result[i] = result[j];
    result[j] = curr;
   }
   return result.join('');
  }
 
 
  function str_reverse5(str) {
   var length = str.length,
       result = [];
   while (length--) {
    result.push(str[length]);
   }
   return result.join();
  }
 
  function str_reverse6(str) {
   var length = str.length,
       pad = length,
       result = new Array(length);
   while (length--) {
    result[pad - length] = str[length];
   }
   return result.join('');
  }

  function str_reverse7(str) {
      var tmp = '';
      for (var i = str.length - 1; i >= 0; i--) {
         tmp += str[i];
      }
      return tmp;
  }
</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
str.split('').reverse().join('')
str_reverse1(str);
pending…
str_reverse2(str)
str_reverse2(str);
pending…
str_reverse3(str)
str_reverse3(str);
pending…
str_reverse4(str)
str_reverse4(str);
pending…
str_reverse5(str)
str_reverse5(str);
pending…
str_reverse6(str)
str_reverse6(str);
pending…
str_reverse7(str)
str_reverse7(str);
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