String Reverse Methods Performance

JavaScript performance comparison

Test case created by Ceane Lamerez and last updated

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    w_reverse = function (_str, nstr, _lt) {
      nstr = '', _lt= _str.length - 1;
      do nstr += _str[_lt];
      while(_lt--);
      return nstr;
    }
    w_reverse2 = function (_str) {
      var nstr = '', _lt= _str.length;
      while(_lt-- && !!~void(nstr+=_str[_lt]));
      return nstr;
    }
    ed_reverse = function (s) {
    for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]);
    return o;
    }
    lame_reverse = function (s) {
    for (var i = s.length, o = ''; i--; o += s[i]);
    return o;
    }
    nonUni_reverse = function (s) {
      return s.split("").reverse().join("");
    },
    m_reverse = function (str, combines, surrogates) {
        //Sourced from Mathias Bynens, to make sure certain reverse unicode characters are correct
        combines = /([\0-\u02FF\u0370-\u1DBF\u1E00-\u20CF\u2100-\uD7FF\uDC00-\uFE1F\uFE30-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF])([\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]+)/g,
        surrogates = /([\uD800-\uDBFF])([\uDC00-\uDFFF])/g;
      combines.test(str) && (str = str.replace(combines, function($0, $1, $2) {return reverse($2) + $1;}).replace(surrogates, '$2$1'));
   
        for (var i = str.length, nstr = ''; i--; nstr+=str[i]);
        return nstr;
    },
    text = "Hi friend!"
};
</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
While reverse
w_reverse(text);
pending…
While reverse 2
w_reverse2(text);
pending…
For Reverse by Edd Mann
ed_reverse(text);
pending…
For Reverse modified
lame_reverse(text);
pending…
Common Reverse (no support for unicode characters!)
nonUni_reverse(text);
pending…
Reverse, Mathaias Bynens
m_reverse(text, false);
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