http://www.perlmonks.org?node_id=250254


in reply to Re: Re: Making a match
in thread Making a match

++ to you and perlplexer. I hadn't realized you could do it that way. Benchmark.pm shows defining the hash is over twice as fast as assigning values to it. The benchmark results on the comparison techniques are more interesting:
if ($hash{$x} == 1) { # always slower than if($hash{$x}) # or if(defined($hash{$x})) } if ($hash{$x}) { # slower than if(defined($hash{$x})) # when $hash{$x} is undefined # faster than if(defined($hash{$x})) # when $hash{$x} is defined }
Here's the benchmark code I used:
#!/usr/bin/perl use strict; use Benchmark; my @list = (10,11,12,13,14,15,17,18,22,23,24,25,26,27,28,29,30,31,32,3 +3,34,35 ); my %hash; @hash{@list} = (1) x @list; timethese(1000000, { 'Hash Defined Miss' => sub { if (defined($hash{1})) { #nop } }, 'Hash Defined Hit' => sub { if (defined($hash{10})) { #nop } }, 'Hash Assigned Miss Truth' => sub { if ($hash{1}) { #nop } }, 'Hash Assigned Miss Equality' => sub { if ($hash{1} == 1) { #nop } }, 'Hash Assigned Hit Truth' => sub { if ($hash{10}) { #nop } }, 'Hash Assigned Hit Equality' => sub { if ($hash{10} == 1) { #nop } } });
Benchmark: timing 1000000 iterations of Hash Assigned Hit Equality, Ha +sh Assigned Hit Truth, Hash Assigned Miss Equality, Hash Assigned Miss Truth, Hash Define +d Hit, Hash Defined Miss... Hash Assigned Hit Equality: 5 wallclock secs ( 1.52 usr + 0.00 sys = + 1.52 CPU) @ 657894.74/s (n=1000000) Hash Assigned Hit Truth: 3 wallclock secs ( 1.29 usr + -0.01 sys = 1 +.28 CPU) @ 781250.00/s (n=1000000) Hash Assigned Miss Equality: 3 wallclock secs ( 1.30 usr + 0.00 sys += 1.30 CPU) @ 769230.77/s (n=1000000) Hash Assigned Miss Truth: 1 wallclock secs ( 1.15 usr + 0.01 sys = +1.16 CPU) @ 862068.97/s (n=1000000) Hash Defined Hit: 1 wallclock secs ( 1.41 usr + 0.00 sys = 1.41 CPU +) @ 709219.86/s (n=1000000) Hash Defined Miss: 2 wallclock secs ( 0.95 usr + 0.00 sys = 0.95 CP +U) @ 1052631.58/s (n=1000000)

-Matt