http://www.perlmonks.org?node_id=629735


in reply to Nested evals - are they evil?

OK, I just made up a quick test case:
use strict; use warnings; use Benchmark 'cmpthese'; cmpthese(10000, { 'eval' => sub { eval_code() }, 'noeval' => sub { no_eval_code() },, }); sub eval_code { my $x = 0; for (1..1000) { eval { $x+=1; } } } sub no_eval_code { my $x = 0; for (1..1000) { $x+=1; } }
And, unless I've missed something blindingly obvious, in this trivial case there is quite an overheard with eval:
Rate eval noeval eval 1495/s -- -62% noeval 3953/s 164% --
But let's tweak that for a real life example. Here's some code where it "dies" one time in ten:
use strict; use warnings; use Benchmark 'cmpthese'; cmpthese(1000000, { 'eval' => sub { eval_code() }, 'noeval' => sub { no_eval_code() },, }); sub eval_code { my $x = 0; for (reverse 0..9) { eval { my $x = 100/$_; }; if ($@) { error_sub(); } } } sub no_eval_code { for (reverse 0..9) { if ($_==0) { error_sub(); } else { my $x = 100/$_; } } }
and here's the benchmark results:
Rate eval noeval eval 67797/s -- -39% noeval 111111/s 64% --
Well. That's still significantly faster. So have I proved eval slows things down, or is this a case specific example that someone can find a counter-example for? I've been bitten by benchmarks on code snippets before, so I'm still wary of this result. Hmmmmm....