in reply to Re^2: Foreach Loop Optimization
in thread Foreach Loop Optimization

Doing a quick benchmark seems to show that it is a little bit more efficient, probably because you are only having to test once. It is certainly more readable.

use strict; use warnings; use Benchmark q{cmpthese}; my @states; push @states, int rand 2 for 1 .. 10000; cmpthese(-5, { tirwhan => sub { foreach my $mf2 ( @states ) { my $lt = $mf2 ? q{processed time} : q{n/a}; } }, upallnight => sub { foreach my $mf2 ( @states ) { my $lt; $lt = q{processed time} if $mf2; $lt = q{n/a} unless $mf2; } }, });

Here's the output

Rate upallnight tirwhan upallnight 22.6/s -- -22% tirwhan 29.1/s 29% --

(Usually when I post benchmarks someone points out that I've got it completely wrong so I'll probably get shot down in flames for this ;-)

Cheers,

JohnGG