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