in reply to Re: Simple Switch statement
in thread Simple Switch statement
to:sub switch{ eval{ goto "case_$_[0]" } or goto default; } for my $expr ( 1 .. 10, 'fred' ) { switch( $expr ); {
but other than that, I must say I like this idiom as well. If you're not interested in performance, that is. Because the performance of the switch like this, is abysmal compared to an identical if/elsif/else structure, as this little benchmark shows:my $switch = sub { eval{ goto "case_$_[0]" } or goto default; }; for my $expr ( 1 .. 10, 'fred' ) { $switch->( $expr ); {
Please note that I changed the print statements to "print STDERR" so that I could send them to the bitbucket. The result of the benchmark:use strict; use Benchmark; timethese( 50000,{ switch => sub { sub switch{ eval{ goto "case_$_[0]" } or goto default; } for my $expr ( 1 .. 10, 'fred' ) { switch( $expr ); { case_1: print STDERR '1'; last; case_2: print STDERR '2'; last; case_3: print STDERR '3'; last; case_4: print STDERR '4'; last; case_5: ; case_6: print STDERR '5 or 6'; last; case_fred: print STDERR 'fred'; last; default: print STDERR "default"; } } }, if => sub { for my $expr ( 1 .. 10, 'fred' ) { if ($expr eq '1') {print STDERR '1'} elsif ($expr eq '2') {print STDERR '2'} elsif ($expr eq '3') {print STDERR '3'} elsif ($expr eq '4') {print STDERR '4'} elsif ($expr eq '5' or $expr eq '6') {print STDERR '5 or 6'} elsif ($expr eq 'fred') {print STDERR 'fred'} else {print STDERR "default"} } }, } );
Benchmark: timing 50000 iterations of if, switch if: 7 wallclock secs ( 5.41 usr + 0.00 sys = 5.41 CPU) @ 92 +42.14/s (n=50000) switch: 43 wallclock secs (39.85 usr + 0.00 sys = 39.85 CPU) @ 12 +54.71/s (n=50000)
So the switch structure is at least 7 times as a comparable id/elsif/else structure. So don't put this in very deep and tight loops!
Liz
Edit by tye, change PRE to CODE around long lines
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Performance - Re: Re: Re: Simple Switch statement
by knexus (Hermit) on Sep 14, 2003 at 15:06 UTC | |
by hnhegde (Novice) on Dec 16, 2014 at 11:25 UTC |