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 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="(.*)">\<$key\>\<\/a\>/;
$data1=$1;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
"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.
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/
s/obliquely/obviously/
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...
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)]);};
Using the hash would be faster and cleaner that wither of the others.