Javascript 中关于 replace() 或 substr() 的性能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9586705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Performance about replace() or substr() in Javascript
提问by Finalfire
I was wondering about Javascript performance about using string.replace() or string.substr(). Let me explain what I'm doing.
我想知道有关使用 string.replace() 或 string.substr() 的 Javascript 性能。让我解释一下我在做什么。
I've a string like
我有一个像
str = "a.aa.a.aa."
I just have to "pop" last element in str where I always know what type of character it is (e.g, it's a dot here).
我只需要“弹出” str 中的最后一个元素,我总是知道它是什么类型的字符(例如,这里是一个点)。
It's so simple, I can follow a lot of ways, like
很简单,我可以按照很多方法,比如
str = str.substr(0, str.length-1) // same as using slice()
or
或者
str = str.replace(/\.$/, '')
Which methods would you use? Why? Is there some lack in performance using this or that method? Length of the string is negligible.
你会使用哪些方法?为什么?使用这种或那种方法是否有一些性能不足?字符串的长度可以忽略不计。
(this is my first post, so if I'm doing something wrong please, notify me!)
(这是我的第一篇文章,所以如果我做错了什么,请通知我!)
回答by Sirko
For performance tests in JavaScript use jsPerf.com
对于 JavaScript 中的性能测试,请使用jsPerf.com
I created a testcase for your question here, which shows, that substr
is a lot faster (at least in firefox).
我在这里为您的问题创建了一个测试用例,这表明substr
速度要快得多(至少在 Firefox 中)。
回答by Phil H
If you just want the last character in the string, then use the subscript, not some replacement:
如果您只想要字符串中的最后一个字符,请使用下标,而不是替换:
str[str.length-1]
回答by Alexander Pavlov
Do you have to do this thousands of times in a loop? If not (and "Length of string is negligible"), any way will do.
您是否必须在循环中执行此操作数千次?如果不是(并且“字符串的长度可以忽略不计”),任何方法都可以。
That said, I'd prefer the first option, since it makes the intention of trimming the last character more clear than the second one (oh, and it's faster, in case you doneed to run this a zillion times. Since in the regex case, you need to not only build a new string but also compile a RegExp and run it against the input.)
也就是说,我更喜欢第一个选项,因为它使修剪最后一个字符的意图比第二个更清楚(哦,它更快,以防您确实需要运行无数次。因为在正则表达式中在这种情况下,您不仅需要构建一个新字符串,还需要编译一个 RegExp 并针对输入运行它。)
回答by Alexander Pavlov
The substr
way should always be faster than any kind of RegExp. But the performance difference should be minor.
这种substr
方式应该总是比任何类型的 RegExp 都快。但性能差异应该很小。
回答by Florian Margaine
When you have this kind of doubt, either pick what you likethe best (style-speaking, as running this only once doesn't matter much), or use http://jsperf.com.
当你有这种疑问时,要么选择你最喜欢的(说风格,因为只运行一次并不重要),要么使用http://jsperf.com。
For this very example, see here why substr is better:-).
对于这个例子,请看这里为什么 substr 更好:-)。