最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is there a faster Reverse String Algorithm for JavaScript? - Stack Overflow

programmeradmin6浏览0评论

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:

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?

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./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?

Share Improve this question asked Jan 9, 2018 at 18:46 Konrad BłachowiczKonrad Błachowicz 611 silver badge5 bronze badges 2
  • Write a binding in C or WebAssembly. – Jonas Wilms 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. – Bekim Bacaj Commented Jan 15, 2018 at 4:38
Add a ment  | 

6 Answers 6

Reset to default 6

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

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;
}

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

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

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 bining the characters. Remember that when you modify arrays by inserting (or removing) elements at the beginning, all other elements must have their index adjusted.

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.

发布评论

评论列表(0)

  1. 暂无评论