++ 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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.