http://www.perlmonks.org?node_id=948159

markseger has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to understand why a block of if...elsif statements seem to be running slow, at least to me. So I conducted a few experiments and don't know enough about the innards of perl to explain why I'm seeing what I'm seeing or how I might be able to improve things.

First the basics - here's a very simple script that executes these statements 1M times inside a subroutine:

#!/usr/bin/perl -w for (my $i=0; $i<1000000; $i++) { test($i) } sub test { my $a=$_[0]; # return; if ($a==1) {} elsif ($a==2) {} elsif ($a==3) {} elsif ($a==4) {} elsif ($a==5) {} elsif ($a==6) {} elsif ($a==7) {} elsif ($a==8) {} elsif ($a==9) {} }
and the difference in the times I see to execute it with and without the return statement commented out is about 3/4 of a second, so that's my approximate baselevel for executing the block of code.

The real question is I have a script that reads /proc/pid/status for all processes on my system, about 200 of them. There are 36 entries in the file and I execute the reading in a loop 1440 times (the equivalent of doing this once a minute for a day, in case anyone cares). This comes to executing that block about 1M times which is the reason for using that number in my test script above.

#!/usr/bin/perl -w my $data; for (my $i=0; $i<1440; $i++) { opendir PROC, '/proc'; while (my $pid=readdir PROC) { next if $pid!~/^\d/; open STAT, "</proc/$pid/status" or next; while ($data=<STAT>) { test($i); } close STAT; } } sub test { my $a=shift; return; if ($a==1) {} elsif ($a==2) {} elsif ($a==3) {} elsif ($a==4) {} elsif ($a==5) {} elsif ($a==6) {} elsif ($a==7) {} elsif ($a==8) {} elsif ($a==9) {} }
I would have expected the difference between running this script with the return statement commented out and not commented out to be on the order of a second or less yet it's actually over 5 seconds. This seems like a huge difference and I'd like to know if anyone can tell me why and more importantly if there's a way to improve things.

-mark