jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
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.
<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>
Ready to run.
Test | Ops/sec | |
---|---|---|
iterative |
| ready |
iterative swapping |
| ready |
built-ins |
| ready |
recursive: reverse(str.substr(1)) + str[0] |
| ready |
recursive: reverse(str.last_half()) + reverse(str.first_half()) |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.