Issue
So I’m looking for the fastest possible Reverse String function.
Here are my function and all the functions that I found on the internet and their perfromance tests:
https://jsperf.com/javascript-reversing-string-performance
It looks like the fastest one (and the prettiest in my opinion) is this:
function reverseString(str) {
return str.split().reverse().join("");
}
But maybe there is even more efficient, faster way to do this?
Solution
There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.
Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.
Solution 1
function reverseString (str) {
return str.split('').reverse().join('')
}
console.time("function test");
reverseString('Hello') // => 0.250ms
console.timeEnd("function test");
Solution 2
function reverseString (str) {
let reversed = '';
for (const character of str) {
reversed = character + reversed
}
return reversed
}
console.time("function test");
reverseString('Hello') // => 0.166ms
console.timeEnd("function test");
Solution 3
function reverseString (str) {
return str.split('').reduce((reversed, character) => character + reversed, '')
}
console.time("function test");
reverseString('Hello') // => 0.133ms
console.timeEnd("function test");
In ES6, you have one more option
function reverseString (str) {
return [...str].reverse().join('')
}
Answered By – Davaakhuu Erdenekhuu
Answer Checked By – Timothy Miller (BugsFixing Admin)