Skip to content Skip to sidebar Skip to footer

Is There A Faster Reverse String Algorithm For Javascript?

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

Solution 1:

This one seems to be even faster:

functionreverseString(str) {
  let reversed = "";
  const l = str.length;
  for(let i = l-1; i >= 0; i--) {
    reversed = `${reversed}${str[i]}`;
  }
  return reversed;
}

Solution 2:

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

functionreverseString (str) {
  return str.split('').reverse().join('')
}

console.time("function test");
reverseString('Hello') // => 0.250msconsole.timeEnd("function test");

Solution 2

functionreverseString (str) {
  let reversed = '';
  for (const character of str) {
    reversed = character + reversed
  }
  return reversed
}
console.time("function test");
reverseString('Hello') // => 0.166msconsole.timeEnd("function test");

Solution 3

functionreverseString (str) {
  return str.split('').reduce((reversed, character) => character + reversed, '')
}
console.time("function test");
reverseString('Hello') // => 0.133msconsole.timeEnd("function test");

In ES6, you have one more option

functionreverseString(str) {
  return [...str].reverse().join('')
}

Solution 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

Solution 4:

function reverseString(str) {
    let reversed = ""for (let i = str.length -1; i >= 0; i--){
        reversed = reversed + str[i]
    }
    returnreversed;
}

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.

Post a Comment for "Is There A Faster Reverse String Algorithm For Javascript?"