在大循环中使用什么具有更高的性能:.indexOf(str) 或 .match(regex)?
我的页面上有这个 array.prototype ,它似乎占用了大量的处理时间:
Array.prototype.findInArray = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
var regexp = new RegExp(".*" + searchStr + ".*");
if (this[i].match(regexp)) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
I have this array.prototype on my page and it seems to be sucking up a lot of processing time:
Array.prototype.findInArray = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
var regexp = new RegExp(".*" + searchStr + ".*");
if (this[i].match(regexp)) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您知道两边都不必有“.*”,对吧? 默认情况下,正则表达式将匹配字符串内的任何位置。 其次,如果您只是搜索常量字符串,并且不需要使用正则表达式提供的任何高级内容,那么使用
.indexOf()
肯定更快。 另外,这样您就不必担心转义具有特殊含义的字符。First of all, you know that you don't have to have the ".*" on either side, right? A regular expression already by default will match anywhere inside the string. Second, if you are just searching for a constant string, and don't need to use any of the advanced stuff that regular expressions offer, then it's definitely faster to use
.indexOf()
. Plus that way you won't have to worry about escaping characters that have special meaning.正则表达式可能会有很大差异。 我想一个简单的、精心设计的正则表达式可能会和indexOf()一样快甚至更快。 另一方面,复杂的正则表达式需要更多的时间,因为它需要做更多的工作。
您还存在一个浏览器实现问题,使问题变得云雾缭绕。 如果没有编写一个定时循环来测量每个浏览器根据您的特定需求进行每种类型的检测所需的时间,您就无法真正得到可靠的答案。
Regular expressions can vary wildly. I imagine that a simple, well-crafted regular expression might work as fast or faster than indexOf(). On the other hand, a complex regular expression would need more time since it's doing more work.
You also have a browser implementation issue clouding matters. Short of writing a timed loop to measure the time taken for each browser to do each type of detection with your specific needs, you can't really get a solid answer.
更糟糕的是你在循环的每次迭代中创建一个新的正则表达式对象 -
在循环外部定义一次,或将其作为参数传递。
此外,对于这种用途,测试比匹配更好更快。
What is worse is you create a new regular expression object on every iteration of the loop-
define it once, outside the loop, or pass it as an argument.
Also, for this use, test is better and quicker than match.