Perl Switch considered painfully slow

The Switch perl modules is much slower than and if/elsif/else block. The below benchmark code puts it at about 40 times slower.

I used this program to generate some test data.
#!/usr/bin/perl

@options = ('a','b','c','d','e','f','g','h','i','j');

for($i=0; $i<1000000; $i++) {
print $options[int(rand($#options))] . "\n";
}

Then I timed these two:
#!/usr/bin/perl

my $a = 0;
while($line = <>) {
chomp $line;
if($line eq 'a') { $a = $a+1; }
elsif($line eq 'b') { $a = $a+2}
elsif($line eq 'c') { $a = $a+3; }
elsif($line eq 'd') { $a = $a+4; }
elsif($line eq 'e') { $a = $a+5; }
elsif($line eq 'f') { $a = $a+6; }
elsif($line eq 'g') { $a = $a+7; }
elsif($line eq 'h') { $a = $a+8; }
elsif($line eq 'i') { $a = $a+9; }
elsif($line eq 'j') { $a = $a+10; }
}

print $a . "\n";

And:
#!/usr/bin/perl

use Switch;

my $a = 0;
while($line = <>) {
chomp $line;
switch($line) {
case 'a' { $a = $a+1; }
case 'b' { $a = $a+2}
case 'c' { $a = $a+3; }
case 'd' { $a = $a+4; }
case 'e' { $a = $a+5; }
case 'f' { $a = $a+6; }
case 'g' { $a = $a+7; }
case 'h' { $a = $a+8; }
case 'i' { $a = $a+9; }
case 'j' { $a = $a+10; }
}
}

print $a . "\n";

Leave a Reply

You must be logged in to post a comment.