When JavaScript regex literals compile

According to the MDN RegExp Guide, regular expression literals are compiled, while RegExp objects created by a constructor call are not.

Now my question is, when does the compilation happen? Because the literal has a unique syntax, it is identified as a regular expression during parsing. This would allow you to compile it once and reuse the result each time it is evaluated, resulting in 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, is this used in practice by any JavaScript engine?

+4
1

MDN , :

.

, , RegExp ( "ab + c" ),

, , . ? , :

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)

. . .

+3

Source: https://habr.com/ru/post/1523377/


All Articles