I ran into a situation today where I was trying to see whether any exceptions were thrown when evaluating a list of objects. In this particular case I didn’t want the exceptions to short circuit the loop, I just needed to know if any were thrown as we iterated over the list. So I wrote this benchmark to see which of two approaches would be faster.
use strict;
use Ouch;
use Benchmark qw(:all);
my @list = (1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1);
timethese(10000, {
'&&=' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
$is_proofed &&= eval { $x ? 1 : ouch(500, 'bad stuff') };
}
},
'$@' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
eval { $x ? 1 : ouch(500, 'bad stuff') };
if ($@) {
$is_proofed = 0;
}
}
}
});
The more exceptions I introduce to the list the worse the $@ approach got, but the &&= approach remained consistently fast. Here are the Benchmark results with just 2 exceptions in the list: