Conrad, Bill (ThomasTech) wrote:

> $Bill Luebkert wrote
> 
> 
>>Paul Rogers wrote:
>>
>>>What's the simplest/shortest way to write an IF statement given that I'm 
>>>looking for the variable to be one of 5 possible choices?
>>>
>>>E.g.,
>>>
>>>if ($x eq 'a' or $x eq 'b' or $x eq 'c or $x eq 'd' or $x eq 'e') {
>>>    blah
>>>}
>>>
>>>I guess what I'm asking for is if there is a way to simplify/shorten this
> 
> 
>>>structure?
>>
>>You could use a RE, but it may be slower :
>>
>>if ($x =~ /^[abcde]$/) {
>>      code
>>
>>if the characters were words :
>>
>>if ($x =~ /^(word1|word2|word3|word4)$/) {
>>      code
> 
> 
> I always thought that RE was faster. In light of this, which of the
> following is better
> 
>       if ( $test =~ /^Start of text/so  ) {
> 
> or
> 
>       if ( substr ( $text , 0 , 13 ) eq 'Start of text' ) {

What are you lazy ?  :)  Try benchmarking it yourself.

use Benchmark qw(cmpthese);

# my $text = "Start of text - some more text\n";
# my $text = "Start of text - some more text Start of text - some more text\n";
my $text = "Start of text - some more text Start of text - some more text Start 
of text - some more text Start of text - some more text\n";
my $count = 5000000;
my $x = 0;

cmpthese ($count, {

        'RE' => sub {
                if ($text =~ /^Start of text/) {
                        $x++;
                }
        },

        'substr' => sub {
                if (substr ($text, 0, 13) eq 'Start of text') {
                        $x++;
                }
        },

        }
);

__END__

I tried 3 different lengths of $text and substr is the clear winner.

Short string:
            Rate     RE substr
RE      969556/s     --   -72%
substr 3443526/s   255%     --

Longer string:
            Rate     RE substr
RE      955292/s     --   -70%
substr 3168568/s   232%     --

Longest string:
            Rate     RE substr
RE      916926/s     --   -70%
substr 3076923/s   236%     --


-- 
  ,-/-  __      _  _         $Bill Luebkert    Mailto:[EMAIL PROTECTED]
 (_/   /  )    // //       DBE Collectibles    Mailto:[EMAIL PROTECTED]
  / ) /--<  o // //      Castle of Medieval Myth & Magic http://www.todbe.com/
-/-' /___/_<_</_</_    http://dbecoll.tripod.com/ (My Perl/Lakers stuff)
_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to