SPUG: Efficiency of Eval

Doug Beaver dougb at scalar.org
Mon Dec 6 19:25:50 CST 1999


On Mon, Dec 06, 1999 at 02:38:54PM -0800, Asim Jalis wrote:
> Is:
> 
>   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.)

Have you tried using Benchmark.pm?  It's pretty good at telling you
stuff like this.  `perldoc Benchmark` for more info.

If you don't want to execute the same code block over and over in order
to determine the cost, you could also use Devel::SmallProf and
Time::HiRes to time execution of the block of code.

I really can't guess which one is faster because block eval is parsed at
compile time, so the speed difference is probably negligible.  I think
you should benchmark the two and see which one is faster on your system,
and if speed matters that much, then use the one that is faster.

If I wanted to implement exceptions, I would choose block eval over
checking the return value of the functions even if block eval was
slower; I think it's a cleaner implementation and more perlish to check
$@ and catch the different exceptions.

Also, there's a module named Exceptions.pm on CPAN, I haven't used it,
but it has try/catch/throw functionality and the syntax looks pretty
good.  You might be able to look at it and get some good ideas.  It
doesn't have perldoc, so you'll have to get your hands a bit dirty and
read the source to figure out how it works.

Doug

-- 
Smithers: I'm afraid we have a bad image, Sir.  Market research shows
          people see you as somewhat of an ogre.
   Burns: I ought to club them and eat their bones!

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    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