3

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?

2
  • Write a binding in C or WebAssembly. Commented Jan 9, 2018 at 18:57
  • 1
    It looks that way, but however elegant in writing and to my best of experience - that's the slowest one of them all. Commented Jan 15, 2018 at 4:38

6 Answers 6

6

This one seems to be even faster:

function reverseString(str) {
  let reversed = "";
  const l = str.length;
  for(let i = l-1; i >= 0; i--) {
    reversed = `${reversed}${str[i]}`;
  }
  return reversed;
}
Sign up to request clarification or add additional context in comments.

Comments

5

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('')
}

2 Comments

Well, your third solution looks to be faster than the first one, thank you!
Dont count on it! These result are only for 1 test, and for 1 word. And you don't know what his/her proccesor was doing at the time. Seriously, I can't even begin to understand why this answer was accepted, as it does not even remotely begin to answer the OP's question of which way is faster THEORETICALLY, not EMPIRICALLY with such poor tests.
3

Based on davaakhuu-erdenekhuu solutions I've created a benchmark so you can test which is the best for you https://jsbench.me/4bkfflcm2z

I've run it on Firefox and Chrome on a Macbook pro 16 Seems like the 1st option was the fastest on Firefox and the 3rd options was the fastest on Chrome

Hope you find it useful

2 Comments

I added Max/Norman's more simple "loop backwards and concat" method into it and it was far, far faster than any of those in Davaakhuu's answer
@MattFletcher found the opposite, 5% slower that the reduce approach
2

I tested my method in Firefox and Chrome and it was the fastest method among the methods given here. I just use simple for loop

function reverseString5(str) {
  let x = '';
  
  for (let i = str.length - 1; i >= 0; --i) {
        x += str[i];
  }
  
  return x;
}

All tests were run here

2 Comments

I bet mine is faster, if you test it ;) Nothing can beat a logical reversal :)
@vitaly-t OMG, isn't it too late? :) BTW you don't return the string. I'm not sure but I believe that in your way I had to call Iterator every time, so I can't store reversed string anywhere and it will be less efficient than the storing reversed string in memory and then just accessing it
1
function reverseString(str) {
    let reversed = ""
    for (let i = str.length -1; i >= 0; i--){
        reversed = reversed + str[i]
    }
    return reversed;
}

Working from the end of the input string is optimal, especially depending on how you go about combining the characters. Remember that when you modify arrays by inserting (or removing) elements at the beginning, all other elements must have their index adjusted.

Comments

1

For any ArrayLike type, the fastest way to reverse is logically, by wrapping it into a reversed iterable:

function reverse<T>(input: ArrayLike<T>): Iterable<T> {
    return {
        [Symbol.iterator](): Iterator<T> {
            let i = input.length;
            return {
                next(): IteratorResult<T> {
                    return i
                        ? {value: input[--i], done: false}
                        : {value: undefined, done: true};
                },
            };
        },
    };
}

Now you can reverse-iterate through any array, string or buffer, without any extra copy or processing for the reversed data:

for(const a of reverse([1, 2, 3])) {
    console.log(a); //=> 3 2 1
}

It is the fastest approach, because you do not copy the data, and do no processing at all, you just reverse it logically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.