您的位置:首页 > Web前端 > JavaScript

一次简单的js正则表达式的性能测试

2015-01-04 19:25 281 查看
最近用到js做一些文本处理,免不了涉及正则表达式,由于文本的规模会达到GB级,速度和还是很关键的。

根据
jsperf 上的测试发现,如果需要用到正则去匹配的话,还是预编译的表达式
precompiled search
表现最好。这是一个比较容易也比较重要的优化项。

看MDN发现有一个
g flag
代表global match也就是尝试所有可能的匹配。MDN上的相关解释如下。

Whether to test the regular expression against all possible matches in a string, or only against the first.

所有的又产生了一个疑问,如果我这需要判断是否存在一个表达式,不需要知道几个,也就是只用
RegExp.test()
,需不需要
g flag
,感觉加上有可能会使速度变慢,但是不确定,写了一个很简陋的性能测试。

var start = +new Date(),
end,
globalRegex = /someone/g,
nonGlobalRegex = /someone/,
testStr = 'This optimization makes the lexer more than twice as fast! Why does this make sense? First, if you think about it in the simplest way possible, the iteration over rules moved from Python code to C code (the implementation of the re module). Second, its even more than that. In the regex engine, | alternation doesnt simply mean iteration. When the regex is built, all the sub-regexes get combined into a single NFA - some states may be combined, etc. In short, the speedup is not surprising.someone';

for (var i = 100000; i >= 0; i--) {
// with a g flag
globalRegex.test(testStr);

// without g flay
// nonGlobalRegex.test(testStr);
}
end = +new Date();

console.log(end - start);

分别去掉注释分别运行发现带
g flag
的需要25-30ms,而不带
g flag
的却需要40+ms,和直觉相反。然后回想了一下
g flag
的作用,接着看文档,发现一个叫做
lastIndex
的属性:

The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match.

得知既然是尝试匹配所有可能,如果没有主动把
lastIndex
清零,则会继续上一次的匹配知道结束。所以以上代码如果是带
g flag
的情况上一次匹配完成,已经到了句末,加入此时
console.log(globalRegex.lastIndex)
会得到
testStr.length
,而且下一次会继续尝试向后匹配,并另计返回false。所以可以理解上述的时间差。

假如把for循环中带
g flag
的情况加一句:

for (var i = 100000; i >= 0; i--) {
// with a g flag
globalRegex.test(testStr);
globalRegex.lastIndex = 0;

// without g flay
// nonGlobalRegex.test(testStr);
}

两种情况的运行结果都在40+ms。

结论:即使加上
g flag
理论上也不影响速度,只需要将
lastIndex
清零,不过清零还是需要消耗的,所以如果只需要匹配判断,可以不用
g flag
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: