in reply to Re: Simple Switch statement
in thread Simple Switch statement

I normally do just as dragonchild suggests, which is indeed right out of holy writ. However, don't be too quick to give up the old if/then/else. While maybe not as clean looking or as cool, the venerable standby can be about 2x as fast, though, admittedly, usually not noticeable unless you are testing thousands of conditions :-)

Switch/case is one of the RARE features I miss from traditionally frowned upon javascript.

Replies are listed 'Best First'.
Re: Re: Re: Simple Switch statement
by Roger (Parson) on Sep 13, 2003 at 01:55 UTC
    I agree with what bradcathey said about if/then/else. Also on testing of simple strings/values. The mundane
    if ($a eq "simple value") { ... }
    runs faster than
    if ($a =~ /^simple value$/) { ... }
    The point is to avoid using regular expressions on simple string testing. Any bit of speed increase in perl is good, especially when it has to be evaluated countless times.

      Ah, but why not:

      for($switch_me) { /bob/ && do { print "Got 'bob'!\n"; break }; /frnak/ && do { print "Got 'frnak'!\n"; break }; $_ == 1 && do { print "Got 1!\n"; break }; print "Got nuttin'!\n"; }

      You can have your cake AND eat it too.

      Alakaboo

        I have constructed the following test case to compare the performance of simple regular expression and simple eq test:

        use Benchmark; @switch_me = qw / bob frnak 1 roger james /; timethese (1000000, { 'test_regex' => ' &test_regex; ', 'test_eq' => ' &test_eq; ' }); sub test_regex() { for(@switch_me) { /bob/ && do { break }; /frnak/ && do { break }; $_ == 1 && do { break }; } } sub test_eq() { for(@switch_me) { $_ eq "bob" && do { break }; $_ eq "frnak" && do { break }; $_ == 1 && do { break }; } }
        The two subroutines are identical except for the string testing bit. The following are the test results:
        Benchmark: timing 1000000 iterations of test_eq, test_regex... test_eq: 8 wallclock secs ( 8.45 usr + 0.01 sys = 8.46 CPU) @ 118161.41/s (n=1000000) test_regex: 10 wallclock secs ( 9.22 usr + 0.01 sys = 9.23 CPU) @ 108307.16/s (n=1000000)
        It's about (118161.41-108307.16)/108307.16 = 10% speed increase in using eq than using regular expression. It's not a great increase, but it's nevertheless faster to use eq than regular expression.