in reply to Re: Hashing it out: defined? exists?
in thread Hashing it out: defined? exists?

Here is how I tested these (correctly, I hope):
#!/usr/bin/perl -w use strict; use Benchmark qw( timethese ); use vars qw( %hash ); @hash{ 'A' .. 'Z', 'a' .. 'z' } = (1) x 52; timethese 100000, { 'defined' => sub { if (defined $hash{X}) { }; }, 'exists' => sub { if (exists $hash{X}) { }; }, 'as is' => sub { if ($hash{X}) { }; }, };


the results:

Benchmark: timing 100000 iterations of as is, defined, exists...
     as is:  1 wallclock secs ( 0.16 usr +  0.00 sys =  0.16 CPU)
            (warning: too few iterations for a reliable count)
   defined:  0 wallclock secs ( 0.16 usr +  0.00 sys =  0.16 CPU)
            (warning: too few iterations for a reliable count)
    exists:  0 wallclock secs ( 0.16 usr +  0.00 sys =  0.16 CPU)
            (warning: too few iterations for a reliable count)

Replies are listed 'Best First'.
Re^3: Hashing it out: defined? exists?
by ikegami (Patriarch) on Sep 02, 2005 at 20:15 UTC

    Changing 100000 to -3 (means 3 seconds) and changin timethese to cmpthese gives:

    Rate defined exists as is defined 1961549/s -- -10% -12% exists 2181802/s 11% -- -2% as is 2236990/s 14% 3% --

    Oddly enough, defined is slower. Then again, this isn't a very accurate test since the condition always evaluates to true. Also, any time loss is so minute compared losses from other inefficiencies that it doesn't matter. Deciding which of these to use based on efficiency is like trying to trying to what kind of gum to buy based on how long it takes to remove the packaging.

      Thanks for the benchmark tips ike. I'm going to go the 'as is' route.
Re^3: Hashing it out: defined? exists?
by eff_i_g (Curate) on Sep 02, 2005 at 20:10 UTC
    Benchmark: timing 500000 iterations of as is, defined, exists...
         as is:  0 wallclock secs ( 0.79 usr +  0.00 sys =  0.79 CPU)
       defined:  2 wallclock secs ( 0.82 usr +  0.00 sys =  0.82 CPU)
        exists:  1 wallclock secs ( 0.76 usr +  0.00 sys =  0.76 CPU)