Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by ikegami (Patriarch)
on Jun 27, 2010 at 20:32 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (9)
As of 2024-04-19 08:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found