Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are JavaScript regular expression literals compiled

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?

like image 870
Johannes Matokic Avatar asked Jan 23 '14 15:01

Johannes Matokic


1 Answers

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.

like image 68
tsikov Avatar answered Oct 05 '22 23:10

tsikov