17

所以我知道在 Javascript 中实例化一个正则表达式会导致它被自动编译,如果该正则表达式存储在一个变量中,它将被重用而无需重新编译。例子:

var re = /[Ff]oo|[Bb]ar/;
"Foo".match(re); // ["Foo"]
"Baz".match(re); // null

然而,重复的正则表达式是重新编译还是 V8 (Chrome/Node.js) 智能地重用它们(就像 PHP 对 preg_* 函数所做的那样)?

function isFooBar(str) {
  return str.match(/[Ff]oo|[Bb]ar/);
}
isFooBar("Foo"); // ["Foo"]
isFooBar("Baz"); // null

所以澄清一下,我知道第一个示例会导致一次正则表达式的编译。但是第二个例子呢?

4

2 回答 2

18

好吧,让我们来了解一下。

// http://stackoverflow.com/questions/3466850/complex-password-regular-expression
function isFooBar(str) {
  return str.match(/^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\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*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$)?(^(?=.*\d)(?=.*[a-z])(?=.*[@#$%^&+=]).*$)?(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?$/);
}
console.time('1');isFooBar("Foo");console.timeEnd('1');
console.time('2');isFooBar("Bar");console.timeEnd('2');

(打开您的控制台并运行上面的代码片段以查看您的浏览器的结果。)

在 Node.js 0.10.36 (V8 3.14.5.9) 上:

1: 65ms
2: 0ms

在 io.js 1.6.3 (V8 4.1.0.27) 上:

1: 32ms
2: 0ms

所以,我想你的问题的答案是肯定的,V8 能够自动缓存正则表达式。


编辑:

即使 V8能够进行这种优化,它实际上也可能不会选择始终使用这种优化。V8 有许多针对不同情况的复杂启发式算法,例如何时内联函数、何时优化函数、何时取消优化函数等。除非您是 V8 开发人员,否则其中许多启发式算法看起来很奇怪或出乎意料或两者。

我自己不是 V8 开发人员,我不知道具体问题的答案,或者是否总是自动缓存正则表达式。但是,即使我知道答案,将来也可能会改变。因此,当您编写代码时,我仍然建议您存储正则表达式,以便清楚该变量的意图是什么。对于上面的示例,这意味着将正则表达式变量从函数中取出isFooBar()

另一个问题是如何创建这个正则表达式。上面和 OP 问题中的示例是用正则表达式 literal声明的。但是,如果您使用new RegExp()构造函数,则不允许V8缓存正则表达式,因为它可能会在运行时更改。

于 2015-04-09T00:47:31.177 回答
0

http://code.google.com/p/v8/issues/detail?id=933#c3

在 Chrome 9 中,我们删除了 RegExp 结果的原始缓存。这意味着我们不再花费不切实际的时间来一遍又一遍地对相同的输入重复相同的操作。最初添加缓存是为了说明太简单的基准(当时包括我们自己的)太容易通过添加这种缓存来“游戏”(这在现实世界的场景中没有区别)。自那以后,大多数基准测试都得到了很大改进,以至于我们决定删除缓存(及其不可避免的开销)。缓存是在 v8 修订版 4083(在 Chrome 5 中发布)中添加的,并在修订版 5755 中删除(将在 Chrome 9 中)

于 2013-09-19T09:29:55.670 回答