JavaScript正则表达式文字何时编译 [英] When are JavaScript regular expression literals compiled

查看:81
本文介绍了JavaScript正则表达式文字何时编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 MDN的RegExp指南正则表达式文字

我的问题是,什么时候进行编译?由于文字具有唯一的语法,因此在解析期间将其标识为正则表达式。这样便可以对其进行一次编译,并在每次对其求值时重新使用结果,从而使两个示例具有(几乎)相同的速度。

My question is now, when does the compilation take place? As the literal has unique syntax it is identified as a regular expression during parsing. This would make it possible to compile it once and reuse the result every time it gets evaluated resulting in the two examples having (almost) the same speed.

var str = "Hello World";

// Example 1
var regExp1 = /[aeiou]+/gi;
for(var i = 0; i < 1000; ++i)
    regExp1.exec(str);

// Example 2
for(var j = 0; j < 1000; ++j)
    /[aeiou]+/gi.exec(str);

任何想法是否被任何JavaScript引擎实际使用?

Any ideas whether this is used in practice by any JavaScript-engine?

推荐答案

MDN文档明确指出:


文字符号在以下情况下提供正则表达式的编译计算表达式。

The literal notation provides compilation of the regular expression when the expression is evaluated.


正则表达式对象,例如new RegExp( ab + c),提供了正则表达式的运行时编译

The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression

确实不是很清楚。您在哪里衡量绩效?我是这样看的:

The test you did are not very clear. Where do you measure performance? This is how I see they should be made:

start = new Date();
for(var j = 0; j < 1000000; ++j)
    /[aeiou]+/gi.exec(str);
console.log(new Date - start);

start = new Date();
regex = new RegExp("[aeiou]+", "gi");
for(var j = 0; j < 1000000; ++j)
    regex.exec(str);
console.log(new Date - start);

这将产生:

147
118

很明显,构造函数比我的测试更快(Chrome)

Clearly, the constructor is faster from my tests (Chrome)

在您的测试中,您根本没有测试构造函数。您只是将第一个测试中的文字分配给变量名称。基本上测试是相同的。

Also in your test you weren't testing the constructor at all. You were just assigning the literal in the first test to a variable name. Basically the tests were identical.

这篇关于JavaScript正则表达式文字何时编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆