#!/usr/bin/perl use strict; use warnings; use Benchmark qw( timethese cmpthese ) ; my @numbers = qw(1 -1 123.1 0.1 Characters); my $swithRefLoop = 'foreach my $number (@numbers) { checkInputStringWithSwitchConditions($number); }'; my $ifAndElsIfRefLoop = 'foreach my $number (@numbers) { checkInputStringWithIfAndElseConditions($number); }'; my $Benchmark = timethese( -10, { IfAndElsIfLoop => $ifAndElsIfRefLoop, SwitchLoop => $swithRefLoop, } ); cmpthese $Benchmark; sub checkInputStringWithSwitchConditions { use Switch; switch ($_[0]) { case /^[+-]?\d+\z/ { print "The $_[0] is a +/- integer\n" } case /^[+-]?(?=\.?\d)\d*\.?\d*(?:e[+-]?\d+)?\z/i { print "The $_[0] is a C float\n" } case /\D/ { print "The $_[0] has nondigits\n" } else { print "Non of the cases where True\n" } } } sub checkInputStringWithIfAndElseConditions { if ( $_[0] =~ /^[+-]?\d+\z/ ) { print "The $_[0] is a +/- integer\n"; } elsif ( $_[0] =~ /^[+-]?(?=\.?\d)\d*\.?\d*(?:e[+-]?\d+)?\z/i ) { print "The $_[0] is a C float\n"; } elsif ( $_[0] =~ /\D/ ) { print "The $_[0] has nondigits\n"; } } __END__ Benchmark: running IfAndElsIfLoop, SwitchLoop for at least 10 CPU seconds... IfAndElsIfLoop: 11 wallclock secs (10.04 usr + -0.00 sys = 10.04 CPU) @ 4954765.54/s (n=49745846) SwitchLoop: 9 wallclock secs (10.04 usr + 0.00 sys = 10.04 CPU) @ 5691789.84/s (n=57145570) Rate IfAndElsIfLoop SwitchLoop IfAndElsIfLoop 4954766/s -- -13% SwitchLoop 5691790/s 15% --