Inline regexps and caching

Richard Cornford Richard at litotes.demon.co.uk
Sat Jan 24 17:42:13 PST 2009


Mark S. Miller wrote:
> Mike Shaver wrote:
>> Firefox and Opera are doing what ES3 requires (s 7.8.5:
>> http://bclary.com/2004/11/07/#a-7.8.5 ),
>
> Correct.
>
>> but I believe that it's being changed in 3.1 to produce a new
>> one each time the literal expression is executed.
>>
>
> Correct. In the meantime, you can change expressions like
>
>    var regexp = /^[^d]*\bd{1,4}\b[^d]*$/g;
>
> into
>
>    var regexp = new RegExp("^[^d]*\\bd{1,4}\\b[^d]*$","g");
>
> Yes, this is ugly. But an ugly program that works is better than
> a pretty one that doesn't.

Ugly, and an example of using a hammer to crack a nut. The issue is 
provoked by the fact that for a regular expression with the global flag 
set the - exec - method employs the regular expression object's - 
lastIndex - property, leaving it set to the end index of the last match 
made. Knowing that suggests that a simple 'solution' would be to 
explicitly set the regular expression object's - lastIndex - property to 
zero before using it. That must be cheaper than creating a new regular 
expression object just for the side effect of then having one with a 
zero - lastIndex - property.

In addition, knowing the mechanism also directs attention towards the 
global flag; does the regular expression being used need to have the 
global flag set in the first place? If the flag is not set then 
subsequent - exec - uses will always start at the zero index. The example 
regular expression used above only appears to be interested in making a 
single match so probably there was never a need to have the flag set.

Richard Cornford. 



More information about the Es-discuss mailing list