in reply to Which is better when doing a simple match?

Why speculate?
#!/usr/local/bin/perl -w use Benchmark; $count = 1_000_000; print "Match eq => ", check_eq(), "\n"; print "Match rx => ", check_rx(), "\n"; timethese( $count, { 'eq' => sub{ check_eq() }, 'rx' => sub{ check_rx() } } ); sub check_eq { my $thing = "thing"; my $i = 0; $i++ if( $thing eq "thing" ); $i; } sub check_rx { my $thing = "thing"; my $i = 0; $i++ if( $thing =~ /^thing$/ ); $i; }
reveals
Match eq => 1 Match rx => 1 Benchmark: timing 1000000 iterations of eq, rx... eq: 15 wallclock secs (14.27 usr + 0.00 sys = 14.27 CPU) @ 70 +093.46/s (n=1000000) rx: 22 wallclock secs (21.08 usr + 0.00 sys = 21.08 CPU) @ 47 +430.83/s (n=1000000)

Replies are listed 'Best First'.
Re: Re: Which is better when doing a simple match?
by Cine (Friar) on Aug 22, 2001 at 00:42 UTC
    And to get the index with, and the two different cases:
    #!/usr/local/bin/perl -w use Benchmark; $count = 1_000_000; my $thing = "thing"; print "Match eq => ", check_eq(), "\n"; print "Match rx => ", check_rx(), "\n"; print "Match idx => ", check_idx(), "\n"; timethese( $count, { 'eq' => sub{ check_eq() }, 'rx' => sub{ check_rx() }, 'idx' => sub{ check_idx() } } ); $thing = "asdjgfakjgfashdf___thing___asklfhklajsdhlajsdf"; print "Match eq => ", check_eq(), "\n"; print "Match rx => ", check_rx(), "\n"; print "Match idx => ", check_idx(), "\n"; timethese( $count, { 'eq' => sub{ check_eq() }, 'rx' => sub{ check_rx() }, 'idx' => sub{ check_idx() } } ); sub check_eq { ($thing eq "thing")?1:0; } sub check_rx { ($thing =~ /thing/)?1:0; } $i = 0; sub check_idx { ((index $thing,'thing') != -1)?1:0; }
    Result:

    Match eq => 1 Match rx => 1 Match idx => 1 Benchmark: timing 1000000 iterations of eq, idx, rx... eq: 4 wallclock secs ( 3.40 usr + 0.66 sys = 4.06 CPU) @ 24 +6305.42/s (n=1000000) idx: 6 wallclock secs ( 4.01 usr + 0.86 sys = 4.87 CPU) @ 20 +5338.81/s (n=1000000) rx: 5 wallclock secs ( 4.30 usr + 0.90 sys = 5.20 CPU) @ 19 +2307.69/s (n=1000000) Match eq => 0 Match rx => 1 Match idx => 1 Benchmark: timing 1000000 iterations of eq, idx, rx... eq: 3 wallclock secs ( 3.38 usr + 0.62 sys = 4.00 CPU) @ 25 +0000.00/s (n=1000000) idx: 6 wallclock secs ( 4.18 usr + 1.05 sys = 5.23 CPU) @ 19 +1204.59/s (n=1000000) rx: 6 wallclock secs ( 4.49 usr + 1.05 sys = 5.54 CPU) @ 18 +0505.42/s (n=1000000)


    T I M T O W T D I