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

本文探讨了JavaScript中正则表达式的性能优化技巧,特别是预编译正则表达式和g标志的影响。通过实验对比了使用与不使用g标志时的性能差异,揭示了lastIndex属性对测试操作的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值