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

最近用到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

    原文作者:2hu10n92hen9
    原文地址: https://segmentfault.com/a/1190000000735725
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞