一次简单的js正则表达式的性能测试
2015-01-04 19:25
281 查看
最近用到js做一些文本处理,免不了涉及正则表达式,由于文本的规模会达到GB级,速度和还是很关键的。
根据
jsperf 上的测试发现,如果需要用到正则去匹配的话,还是预编译的表达式
看MDN发现有一个
Whether to test the regular expression against all possible matches in a string, or only against the first.
所有的又产生了一个疑问,如果我这需要判断是否存在一个表达式,不需要知道几个,也就是只用
分别去掉注释分别运行发现带
The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match.
得知既然是尝试匹配所有可能,如果没有主动把
假如把for循环中带
两种情况的运行结果都在40+ms。
结论:即使加上
根据
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
相关文章推荐
- JavaScript (js) 正则表达式 测试器
- 简单的js正则表达式验证数字等
- jquery通过id或name获取标签的值,以及简单的js正则表达式
- 毕业设计(七)---正则表达式通过js表单验证,快速注册流程,简单MD5加密
- js正则表达式(简单例子)
- trim原型函数看js正则表达式的性能
- 正则表达式 jquery js 只能输入中文和汉字,正则表达式禁用英文26个字母 通达OA测试
- 简单的JTML+JS验证用户名、电话号码格式_JS自定义function_正则表达式
- JS正则表达式学习一:简单入门
- jquery通过id或name获取标签的值,以及简单的js正则表达式(笔记)
- 简单的正则表达式http://www.cainiao8.com/web/js_note/js_regular_expression.html
- 递归性高或者逻辑简单、性能要求严格、维护人数多的字符串分析,尽量避免正则表达式
- 简单的用js实现过滤多余字符的正则表达式
- 测试过的JS正则表达式
- 简单的用js实现过滤多余字符的正则表达式
- 简单js验证和正则表达式
- 关于JS通过正则表达式循环检测多个Email格式_已经测试通过.
- 简单的代码片段性能测试 -- 顺便测一下正则和异常的性能(使用循环测试做比较)
- js--javascript 简单的正则表达式
- Js正则表达式学习之test和compile的简单介绍