When are JavaScript regular expression literals compiled

家住魔仙堡 提交于 2020-01-13 02:31:02

问题


According to MDN's RegExp Guide regular expression literals are compiled while RegExp objects created by calling the constructor are not.

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);

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


回答1:


The MDN docs clearly state that:

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

and

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);

This produces:

147
118

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.



来源:https://stackoverflow.com/questions/21312976/when-are-javascript-regular-expression-literals-compiled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!