Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Regexp optimization - /o option better than precompiled regexp?

by ikegami (Pope)
on Jun 27, 2010 at 20:32 UTC ( #846804=note: print w/ replies, xml ) Need Help??


in reply to Regexp optimization - /o option better than precompiled regexp?

Patterns without interpolation are compiled when their quoting operator (m//, s///, qr//) is compiled. /o shouldn't matter one bit for those, so I won't discuss them.

Patterns with interpolation are compiled when their quoting operator (m//, s///, qr//) is executed.

Perl caches compiled regex patterns to avoid needless recompilation in situations like the following:

# Compiles each pattern once since m// realises # you're using the same pattern twice in a row. for my $re (qw( foo bar )) { for (1..2) { /$re/ } }

A match or substitution operator can only resuse the last regex is compiled, so the following isn't efficient:

# Compiles each pattern twice for (1..2) { for my $re (qw( foo bar )) { /$re/ } }

You can use qr// to precompile a pattern.

# Compiles each pattern once my @res = map qr/$_/, qw( foo bar ); for (1..2) { for my $re (@res) { /$re/ } }

Note that Perl currently flattens and recompiles compiled patterns interpolated into another pattern.

# Doesn't recompile $re if it's a qr//. /$re/ # Stringifies and recompiles $re if it's a qr//, # but it should be subject to the caching mentioned above. /x$re/

This should be optimised in the future.


Comment on Re: Regexp optimization - /o option better than precompiled regexp?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://846804]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (11)
As of 2015-07-08 04:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (94 votes), past polls