From: <[EMAIL PROTECTED]> > Well, > > All the above said answers are perfectly fine, but just to make it > more efficient what we can do is, we can avoid the if statement or ?: > operator. > > This is because whenever we go for a decision statement, it takes some > extra processing time.
Whenever we index an array it takes some extra processing time as well. > A solution to avoid using if or ?: is as follows: > > #!/usr/bin/perl > use strict; > > my @string = ("Even", "Odd"); > print $string[$ARGV[0]%2]; > > Well it might look like the savings in time is less, but if you > consider that this code is inside a loop which will run for several > iterations, you are sacing lot of time.... Hence the program becomes > more efficient. Before you say something like this you should test it: use Benchmark; sub withIf { my $number_is = ''; for (1..100000) { if ($_ % 2) { $number_is = 'Odd'; } else { $number_is = 'Even'; } } } sub withQm { my $number_is = ''; for (1..100000) { $number_is = ($_ % 2) ? 'Odd' : 'Even'; } } sub withIfAnd { my $number_is = ''; for (1..100000) { if ($_ & 1) { $number_is = 'Odd'; } else { $number_is = 'Even'; } } } sub withQmAnd { my $number_is = ''; for (1..100000) { $number_is = ($_ & 1) ? 'Odd' : 'Even'; } } my @what = qw(Even Odd); sub withAry { my $number_is = ''; for (1..100000) { $number_is = $what[$_ % 2]; } } sub withAryAnd { my $number_is = ''; for (1..100000) { $number_is = $what[$_ & 1]; } } timethese 100, { withIf => \&withIf, withQm => \&withQm, withIfAnd => \&withIfAnd, withQmAnd => \&withQmAnd, withAry => \&withAry, withAryAnd => \&withAryAnd, } Benchmark: timing 100 iterations of withAry, withAryAnd, withIf, withIfAnd, withQm, withQmAnd... withAry: 6 wallclock secs ( 5.67 usr + 0.00 sys = 5.67 CPU) @ 17.63/s (n=100) withAryAnd: 5 wallclock secs ( 5.20 usr + 0.02 sys = 5.22 CPU) @ 19.16/s (n=100) withIf: 6 wallclock secs ( 6.09 usr + 0.01 sys = 6.11 CPU) @ 16.37/s (n=100) withIfAnd: 6 wallclock secs ( 5.77 usr + 0.00 sys = 5.77 CPU) @ 17.35/s (n=100) withQm: 5 wallclock secs ( 5.05 usr + 0.00 sys = 5.05 CPU) @ 19.81/s (n=100) withQmAnd: 5 wallclock secs ( 4.73 usr + 0.00 sys = 4.73 CPU) @ 21.12/s (n=100) (Using Perl v5.8.0 ActiveState build 805 on Win2k server) So it seems the ?: is actually fastest ;-) Jenda ===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz ===== When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>