SPUG: Efficiency of Eval
Asim Jalis
ajalis at beryllium.cobaltgroup.com
Mon Dec 6 19:44:30 CST 1999
Charles DeRykus writes:
> > eval { some_function_which_calls_die_on_error ($a) ; <stuff> ; }
> > if ($@) { <handle-exception> ; }
> >
> > more efficient, or is:
> >
> > $r = some_function_which_returns_non_zero_on_error ($a) ;
> > if ($r != 0) { <handle-exception> }
> > else { <stuff> . . . <stuff> ; }
> >
> > more efficient (in terms of speed). (Ignore code typos.)
>
> The simple return will be more efficient. Perl's
> C<eval> is doing a setjump(3C),longjump(3C) under the
> covers which will involve the added overhead of saving
> and potentially having to restore the stack environment
> if there's an exception.
>
> Even, if there's no exception, the simple return
> appears to be bit faster:
>
> use Benchmark;
> timethese( 1_000_000,
> {
> 'eval', sub { eval { 1 }; },
> 'return ', sub { 1 }
> }
> Benchmark: timing 1000000 iterations of eval, return ...
> eval: 48 secs (43.62 usr 0.00 sys = 43.62 cpu)
> return : 21 secs (20.20 usr 0.00 sys = 20.20 cpu)
Neat package.
I ran your code with some modifications:
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:
Benchmark: timing 10000000 iterations of eval, return ...
eval: 45 secs (38.98 usr 0.25 sys = 39.23 cpu)
return: 49 secs (38.56 usr 0.44 sys = 39.00 cpu)
So eval was actually marginally faster.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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