-noUser-
icon 5
正则表达式中加入()会影响性能的疑问
已解决
正则表达式中加()和不加的区别
Web前端
发布于 2021-05-13 13:53
887浏览

在昨天开发中,使用正则表达式。代码如下: var start = +new Date(), end, globalRegex = /(\\r\\n)|(\\n\\r)|(\\r)|(\\n)+/g, nonGlobalRegex = /\\r\\n|\\n\\r|\\r|\\n+/g, testStr = 'This optimization makes the lexer more\r\n than twice as fast! Why does this make sense?\r\n First, if you think about it in the simplest way possible, the iteration over rules moved from\r\n Python cod'; for (var i = 10000; i >= 0; i--) { globalRegex.test(testStr); } end = +new Date(); console.log("=----------------匹配使用时间:"+(end - start)); 发现不加小括号的会比加小括号的时间短,有点想不明白为什么,而且相差的还挺多的。

在昨天开发中,使用正则表达式。代码如下:
var start = +new Date(),
end,
globalRegex = /(\r\n)|(\n\r)|(\r)|(\n)+/g,
nonGlobalRegex = /\r\n|\n\r|\r|\n+/g,
testStr = ‘This optimization makes the lexer more\r\n than twice as fast! Why does this make sense?\r\n First, if you think about it in the simplest way possible, the iteration over rules moved from\r\n Python cod’;
for (var i = 10000; i >= 0; i–) {
globalRegex.test(testStr);
}
end = +new Date();
console.log("=----------------匹配使用时间:"+(end - start));

发现不加小括号的会比加小括号的时间短,有点想不明白为什么,而且相差的还挺多的。

在昨天开发中,使用正则表达式。代码如下:
var start = +new Date(),
end,
globalRegex = /(\r\n)|(\n\r)|(\r)|(\n)+/g,
nonGlobalRegex = /\r\n|\n\r|\r|\n+/g,
testStr = ‘This optimization makes the lexer more\r\n than twice as fast! Why does this make sense?\r\n First, if you think about it in the simplest way possible, the iteration over rules moved from\r\n Python cod’;
for (var i = 10000; i >= 0; i–) {
globalRegex.test(testStr);
}
end = +new Date();
console.log("=----------------匹配使用时间:"+(end - start));

发现不加小括号的会比加小括号的时间短,有点想不明白为什么,而且相差的还挺多的。

编写答案
回答问题, 请先登录
1条回答
0
享学课堂-飘哥
2021-05-13 16:48

this is good question! 其实这不是一个前端的问题 这是一个正则表达式的问题,重点在于小括号的在正则的定义,小括号不光是提高优先级的,还有一个作用是捕获符号,也就是说这个内容需要单独捕获单独记录.所以因为这个捕获机制的存在导致效率有一定的影响,你也可以通过match方法甚至是$1-$9来获取部分捕获内容 ![image.png](https://static-club.oss-cn-shanghai.aliyuncs.com/bbs/bbs_1620895730520.png)

this is good question!
其实这不是一个前端的问题
这是一个正则表达式的问题,重点在于小括号的在正则的定义,小括号不光是提高优先级的,还有一个作用是捕获符号,也就是说这个内容需要单独捕获单独记录.所以因为这个捕获机制的存在导致效率有一定的影响,你也可以通过match方法甚至是$1-$9来获取部分捕获内容
image.png

this is good question!
其实这不是一个前端的问题
这是一个正则表达式的问题,重点在于小括号的在正则的定义,小括号不光是提高优先级的,还有一个作用是捕获符号,也就是说这个内容需要单独捕获单独记录.所以因为这个捕获机制的存在导致效率有一定的影响,你也可以通过match方法甚至是$1-$9来获取部分捕获内容
image.png

提问者
学习的人
问题数: 2 个
相似问题
如何提取Roundcube Webmail的接口
1
1 回答
已解决
使用ie 批量下载文件 只下载最后一个文件
5
1 回答
已解决
ios html audio播放问题
5
1 回答
已解决
npm 生成的环境变量缺失
20
1 回答
已解决
react 最骚的修改class 的方法
1
1 回答
已解决
js 给 vue data函数赋值
5
2 回答
已解决
关注
回答
收藏