in reply to How expensive is eval { }?

A simple benchmark indicates that the overhead isn't very much (unless the benchmark is completely flawed of course). Consider:

use strict; use warnings; use Benchmark qw(cmpthese); cmpthese ( -1, { BareFor => \&dofor, ExceptFor => \&doefor, ForExcept => \&dofore, } ); sub dofor { my $sum = 0; for (1 .. 1000) { $sum += $_; $sum += $_; $sum += $_; } } sub dofore { my $sum = 0; for (1 .. 1000) { eval {$sum += $_;} } } sub doefor { my $sum = 0; eval { for (1 .. 1000) { $sum += $_; $sum += $_; $sum += $_; } } }

Prints:

Rate BareFor ExceptFor ForExcept BareFor 1626/s -- -2% -11% ExceptFor 1661/s 2% -- -9% ForExcept 1834/s 13% 10% --

which indicates that the eval overhead is close to the cost of 2 += operations - not a whole lot in other words!


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: How expensive is eval { }?
by moritz (Cardinal) on Apr 17, 2008 at 09:33 UTC
    This benchmark result seems to vary strongly with the platform and/or perl version.

    Debian GNU/Linux i386 (32 bit, SMP):

    $ perl5.8.8 foo.pl Rate ForExcept BareFor ExceptFor ForExcept 2511/s -- -34% -34% BareFor 3794/s 51% -- -1% ExceptFor 3829/s 52% 1% -- $ perl5.10.0 foo.pl Rate ForExcept BareFor ExceptFor ForExcept 2393/s -- -29% -30% BareFor 3350/s 40% -- -2% ExceptFor 3429/s 43% 2% --

    That's quite different from the 2% .. 13%.

    Any idea why the differences between the perl versions and platforms are that big?

      No real idea, but bear in mind that most likely we are looking at only a few instructions' execution time difference between each case so they could be highly sensitive to optimization or modest differences in instruction timing between different processors (I ran my tests on a Turion64 powered laptop btw).

      Beyond indicating that the eval overhead is small enough to be discounted in most practical contexts, the benchmark really doesn't tell us very much - except that you can't trust benchmarks very much for this sort of fine grain comparison. The important thing to note is that the eval costs much less than 1 micro-second.


      Perl is environmentally friendly - it saves trees