SPUG: Efficiency of Eval

Asim Jalis ajalis at beryllium.cobaltgroup.com
Tue Dec 7 11:51:35 CST 1999


Charles DeRykus wrote:
> Asim Jalis wrote:
> > use Benchmark;
> > timethese( 10_000_000,
> >              {
> >               'eval',    sub { eval { sub { die    ; }; } },
> >               'return',  sub { eval { sub { return ; }; } },
> >              }
> > );
> 
> > comparing the whole eval-die cycle with the call-return cycle and got:
> > ...
> > So eval was actually marginally faster.
> 
> Um, no. That would just create the code ref's and eliminate
> the runtime where the real bottlenecks lurk.
> 
> My benchmark was probably flawed too in a different way.
> For instance, something like C<sub { 1 }> may be optimized
> away. I'm convinced though that the 'eval' will be be slower
> and, markedly, if an exception occurs.

Good point. Here's another attempt:

  use Benchmark;
  sub die_occurs    { die;      }
  sub return_occurs { return 1; }
  timethese( 1_000_000,
               {
                'eval',    sub { eval { die_occurs(); } },
                'return',  sub { $r = return_occurs();  }
               }
  );

The output here was:

Benchmark: timing 1000000 iterations of eval, return...
      eval: 35 secs (15.27 usr  5.27 sys = 20.54 cpu)
    return:  7 secs ( 4.17 usr  0.07 sys =  4.24 cpu)

So eval-die is significantly more expensive than call-return. 

However, I wonder if this changes when if you have nested calls, in
which case die will pop all the functions off the stack at once while
return will have to return from each one individually.

Personally I prefer eval-die because then the return value can be used
for something more useful such as data, and the functions in between
the catcher and the thrower don't have to catch the error code and
pass-it-on.

Asim

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list