string reverse
JavaScript performance comparison
Info
Examining various algorithms for string reversal.
NOTE: some of the methods, using recursion, have upper bounds on how long the string to be reversed can be, before the engine/browser will fail by running out of stack space for the recursion. Use recursion with caution.
Preparation code
<script>
var test_str = "",
tmp;
for (var i = 0; i < 3000; i++) {
test_str += String.fromCharCode((i % 26) + 97);
}
function string_reverse_1(str) {
var new_str = "";
for (var i = str.length - 1; i >= 0; i--) {
new_str += str.charAt(i);
}
return new_str;
}
function string_reverse_2(str) {
if (str.length < 1) return "";
str = str.split(""); // make the string an array!
var tmp, len = str.length,
half_index = Math.floor(len / 2) - 1;;
for (var i = 0; i <= half_index; i++) {
tmp = str[len - i - 1];
str[len - i - 1] = str[i];
str[i] = tmp;
}
return str.join(""); // make the array a string again
}
function string_reverse_3(str) {
return str.split("").reverse().join("");
}
function string_reverse_4(str) {
if (str.length < 2) return str;
return string_reverse_4(str.substr(1)) + str.charAt(0);
}
function string_reverse_5(str) {
if (str.length < 2) return str;
var half_index = Math.ceil(str.length / 2);
return string_reverse_5(str.substr(half_index)) + string_reverse_5(str.substr(0, half_index));
}
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
iterative |
|
pending… |
iterative swapping |
|
pending… |
built-ins |
|
pending… |
recursive: reverse(str.substr(1)) + str[0] |
|
pending… |
recursive: reverse(str.last_half()) + reverse(str.first_half()) |
|
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:
- Revision 1: published by Kyle Simpson
- Revision 2: published
- Revision 3: published by Pointy
- Revision 4: published
- Revision 5: published
0 comments