是否有更快的JavaScript反向字符串算法? [英] Is there a faster Reverse String Algorithm for JavaScript?

查看:76
本文介绍了是否有更快的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.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("");
}

但是也许有更有效,更快捷的方法吗? p>

But maybe there is even more efficient, faster way to do this?

推荐答案

由于JavaScript没有内置的反向函数,因此可能有数十种不同的方法可以做到这一点,但不包括内置的反向函数。
下面是我解决JavaScript中的字符串反转问题的三种最有趣的方法。

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.

解决方案1 ​​

function reverseString (str) {
  return str.split('').reverse().join('')
}

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

解决方案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");

解决方案3

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

在ES6中,您还有一个选择

In ES6, you have one more option

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

这篇关于是否有更快的JavaScript反向字符串算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆