Link to home
Start Free TrialLog in
Avatar of saibsk
saibsk

asked on

Changing if to switch case in Perl

I wrote the following code using if else statements.

If I change the above statements to switch cases will it be faster or will they be the same speed. If change to switch will make it faster please advise how to do it.
if ($key eq "Id"){
print "i m inside id\n";
$data1 = "index.cfm?fuseaction=display&Instance=2&ssrid=x44249b495ca194b695506cd6305c4b4d";
}
elsif ($key eq "Inf"){
$data1 = "index.cfm?fuseaction=display&Instance=2&ssrid=xb76de7b59f8b0d3fc600314145cd7ca7";
}
elsif ($key eq "Purp"){
$data1 = "index.cfm?fuseaction=display&Instance=2&ssrid=x6a7ac11fb39acc7cf7f722134aff070b";
}
else{
my $content1 = get("http://www.iso20022.org/standardsrepository/index.cfm?FuseAction=list&Instance=2&NameOpt=contains&view=e&Name=$key");
$content1 =~ /<A href="(.*)">\&lt;$key\&gt;\<\/a\>/;
$data1=$1;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of FishMonger
FishMonger
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To answer your question more directly, using a switch statement would be the same as the if/elsif/else statement.  The advantage of it is that it's a cleaner syntax.

Using the hash would be faster and cleaner that wither of the others.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
"I ran some tests, and found switch to be slower by ~25-30 times."

That surprises me, I would have sworn that they would be almost the same, but obliquely not since the switch statement has the overhead of calling the sub ans its if/elsif/else blocks are more complex.
Humm, the perils of using a spell checker with my eyes half closed. :)

s/obliquely/obviously/
Avatar of Adam314
Adam314

I ran the tests on just one machine, which happened to be a windows machine.  I ran the comparisons 4 times (in case the os did something in the background that would affect the results).  The times look pretty consistent - but I don't know that the switch will always be slower.  If you run the same test, post your results.

Note: When I was running the tests, I randomly selected a key out of (Id, Inf, Purp), never running the else block...


use Time::HiRes 'time';
my @Keys = (qw(Id Inf Purp));
for(1..10000) {Using_if($Keys[rand(3)]);};
for(1..10000) {Using_switch($Keys[rand(3)]);};

Open in new window