in reply to if-else vs. tertiary effieciency?
First of all, i'd write:
print $var ? 'yes' : 'no'
btw. it's a 'ternary' operator. I cannot agree with your results, my perl (5.6.1 and 5.8.0) lets ?: be only about 13% faster:
use Benchmark qw/cmpthese/; our @values = (1,0,undef,50,'yes','no','0E0',0e0,0); my $subs = { ifelse => sub {foreach(@values){ my $x; if($_){$x = 'yes'} else {$x = 'no'} }}, trinary => sub {foreach(@values){ my $x; $x = $_ ? 'yes' : 'no' }}, }; $_->() for values %$subs; cmpthese( $ARGV[0] => $subs );
And to finally (not) answer your question: The ?: operator is much "lighter" than if-else, it is one expression without scope, whereas the if-block can have it's own lexicals. If you wanted to have the functionaltiy of if-else in a ?: construct, you'd have to use do BLOCK, which already slows down the whole thing...
UPDATE: Aristotle is of course right about the "ternary" operator.
--
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: if-else vs. tertiary effieciency?
by Aristotle (Chancellor) on Sep 14, 2002 at 15:18 UTC | |
by MrNobo1024 (Hermit) on Sep 14, 2002 at 15:51 UTC | |
by Aristotle (Chancellor) on Sep 14, 2002 at 15:59 UTC | |
by fruiture (Curate) on Sep 14, 2002 at 15:23 UTC | |
by kabel (Chaplain) on Sep 14, 2002 at 19:11 UTC | |
|
Re: Re: if-else vs. tertiary effieciency?
by blaze (Friar) on Sep 14, 2002 at 23:15 UTC | |
by rir (Vicar) on Sep 15, 2002 at 03:38 UTC | |
by blaze (Friar) on Sep 15, 2002 at 05:31 UTC | |
by Aristotle (Chancellor) on Sep 15, 2002 at 07:43 UTC |