SPUG: Is a case statement or an if-elsif-else statement faster?

Jacinta Richardson jarich at perltraining.com.au
Wed Aug 10 19:04:30 PDT 2005

Duane Blanchard wrote:
> I have a series of if statements that should be collapsed into a
> single case statement or an
> if-elsif-elsif-elsif-elsif-elsif-elsif-elsif-elsif-else statement. Is
> one faster than the other?

Intuitively I'd suggest that if, elsif, elsif ... is faster than using
Switch.pm's case.  Unless things have changed dramatically (possible, I haven't
paid attention to Switch.pm recently) Switch is a source filter, changing your
case statement into a set of if, elsif ... else statements during compilation.

Having said that, clarity of code and maintainability should be more important
than the very little speed up you'll get by avoiding Switch.pm.  Well written
switch code is much easier, for me, to read than a cascade of if/elsif/else
statements.  Unless you're putting a lot of code in the then blocks.


   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |

More information about the spug-list mailing list