> (mystery: how
> can filling in $& be a lot slower than filling in $1?)

It isn't.  It's the same.  $1 might even be more expensive than $&.

It appears that many people don't understand the problem with $&.  I
will try to explain.

Maintaining the information required by $1 or $& slows down the regex
match, possibly by as much as forty to sixty percent, or more.  (How
much depends on details of the regex and the target string.)

For this reason, Perl has an optimization in it so that if you never
use $& anywhere in your program, Perl never maintains the information,
and every regex in your program runs faster.

But if you do use $& somewhere, Perl cannot apply the optimization,
and it must compute the $& information for every regex in the program.
Every regex becomes much slower.

In particular, if you load a module whose author happened to use $&,
all your regexes get slower, which might be an unpleasant surprise,
since you might not be aware of the cause.

A regex with backreferences is *also* slow.  But using backreferences
in one regex does not make all the *other* regexes slow.  If you have

        /(...)/   # regex 1
        /.../     # regex 2

Perl knows that it must compute the backreference information for
regex 1, and knows that it can skip computing the backreference
information for regex 2, because regex 2 contains no parentheses.

If you use a module that contains regexes that use backreferences,
those regexes run slowly, but there is no effect on *your* regexes.

The cost is just as high for backreferences as for $&, but the
backreference cost is paid only by regexes that actually need it.

The $& cost is paid by every regex in the entire program, whether they
used it or not.  This is because Perl has no way to tell which regexes
use $& and which do not. 

One of Uri's suggestions in RFC 158 was to compute $& only for regexes
that have a /k modifier.  This would solve the $& problem because Perl
would compute $& only when asked to, and not for every other regex in
the rest of the program.

Reply via email to