【问题标题】:Which regexp is faster? [closed]哪个正则表达式更快? [关闭]
【发布时间】:2015-12-13 20:27:28
【问题描述】:

如果我想匹配Aa,以下哪个正则表达式会更快找到它?

/[Aa]/

/A/i

如何 many steps it 是怎么做的?

【问题讨论】:

  • @TiesonT.:我在任何地方都没有看到性能测试组件。请给我看。
  • 我怀疑投反对票是因为无法明确回答问题。或者也许是因为它毫无意义;您要问的是永远不会对性能产生明显影响的微优化。
  • @AlanMoore:这个问题有三个可能的答案:first onesecond onethey are the same。我清楚地知道这是微优化。这就是为什么我要求提供任何资源,在那里我可以测试更复杂的示例。请注意,这是一个次要问题,还没有人回答主要问题。

标签: javascript regex


【解决方案1】:

尝试像这样检查它:

function time_my_script(script) {
    var start = window.performance.now();
    script();
    return window.performance.now() - start;
}

time_a = time_my_script(function() {
    var text = 'This is a test string, make it a long one to actually test well';
    var patt = new RegExp(/[Aa]/);
    var res = patt.test(text);
});

time_b = time_my_script(function() {
    var text = 'This is a test string, make it a long one to actually test well';
    var patt = new RegExp(/A/i);
    var res = patt.test(text);
});

console.log('Time A ' + time_a);
console.log('Time B ' + time_b);

JSFiddle:https://jsbin.com/gasayarivu/edit?js,console

PS:
使用异步脚本,这可能会有点困难。

【讨论】:

  • 不错的功能。如果你不介意,我会收集它。
  • 你的意思是“正确”?好吧,我想我不介意 XD
  • 我的意思是“收集”、“收集”、“保存”。
  • 噢,在这种情况下,当然可以!这就是 SO 的意义 ?
  • 您肯定希望在循环中运行几次以获得合理的估计。尽管 A 似乎比 B 慢了很多,但方差还是很大的。
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2017-11-13
相关资源
最近更新 更多