Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Trinary or If'n'Else?

by chromatic (Archbishop)
on Dec 22, 2000 at 06:11 UTC ( [id://47986]=note: print w/replies, xml ) Need Help??


in reply to Trinary or If'n'Else?

Run perl -MO=Deparse on your code to see what it looks like after optimization. On Perl 5.5.3 on my box, it doesn't change it.

As for a benchmark, here's what I used:

sub trinary { my $a = 1; my $b = 0; return $a > $b ? $a : $b; } sub if_else { my $a = 1; my $b = 0; if ($a > $b) { return $a; } else { return $b; } } use Benchmark; timethese(500000, { trinary => \&trinary, if_else => \&if_else, });
You can play with different ways of constructing the if-else block. With 500,000 iterations, the ternary is 4% faster. I wouldn't worry about a difference like that.

Removing the else flips it the other way:

sub if_else { my $a = 1; my $b = 0; return $a if $a > $b; return $b; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://47986]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-24 19:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found