in reply to Why this code run faster?

The /o modifier isn't doing anything. Try running with and without it; when I did, there wasn't any difference. That modifier only affects patterns that have a variable interpolated in them, and your patterns don't.

The /g modifier seems to be the one that's making the difference, but I don't see why. I'd actually expect it to work the opposite way from what it does.

You might want to see also No More Meaningless Benchmarks! The operations involved are ridiculously fast, so I'm not sure how useful (or accurate) it is to compare them. Consider:

use Benchmark qw( cmpthese ); cmpthese( 10_000_000, { lower => sub { 'network' =~ /^network$/ }, upper => sub { 'networK' =~ /^networK$/ } } ); __END__ Rate lower upper lower 3174603/s -- -9% upper 3496503/s 10% --

Matching uppercase is faster than lowercase? Seriously?

I tried comparing literally the same subs, and there was still a 1% difference.

Adding an explicit scalar context brought the difference down a bit, but I'm not sure because the results aren't very consistent. In fact, I'd call them downright erratic.

All that being said, if someone can explain why a /g would make the pattern faster, I'd be very interested to hear. As it stands, I think there isn't a meaningful or consistent difference.

Replies are listed 'Best First'.
Re^2: Why this code run faster?
by ikegami (Patriarch) on Nov 08, 2007 at 17:27 UTC
    /g in scalar context would make every second match fail.
    sub f { 'network' =~ /^network$/g } print f()?1:0, "\n" for 1..6;
    1 0 1 0 1 0

    The failing match should be faster than the succeeding match.

      Good eyes. When I change the test from if ($phrase2 =~ /^network$/g) {} to while ($phrase2 =~ /^network$/g) {}, the time went from 2.70s to 5.97s. This is in line with what I'd expect -- if 5E6 successful matches and 5E6 failed matches take 2.7s on my CPU, the while loop, consisting of 1E7 successes and 1E7 failures, should take about twice as long.

      Thank you guys! You are really help me again.

      And of course special thanks to ikegami.

Re^2: Why this code run faster?
by gamache (Friar) on Nov 08, 2007 at 17:27 UTC
    When I tested with and without /g, the regex with /g would complete its run in 2.75 +/- 0.1 seconds, and without /g completed in 3.70 +/- 0.1 seconds on the CPU. This result was consistent across runs, and did not depend on the case of the regex.