Perl is doing an unseen optimization here. Since you're working with a variable with its name spelled out in the code, Perl knows immediately what scalar you are wanting to access, without having to do much in the way of symbol table lookups. I
think the original poster was wanting to know the difference between setting and accessing a scalar in a hash versus a
soft reference to a variable, the name of which might not be known. Here's some Benchmark code that takes that into consideration. These results are closer to what I expect, but I'm actually surprised that soft references performed
this poorly. Note that I may easily be mistaken about the original poster's requirements here (named variable versus a soft reference), but I think with both of our data, there's enough information to see which is more efficient. Regardless, we're talking about an operation that takes a miniscule amount of time. If we save a few microseconds of execution time, that doesn't add up to anything significant, ever.
Benchmark: running array, hash, softref, each for at least 10 CPU seco
+nds...
array: 11 wallclock secs (10.50 usr + 0.00 sys = 10.50 CPU) @ 32
+119.33/s (n=337253)
hash: 11 wallclock secs (10.30 usr + 0.00 sys = 10.30 CPU) @ 22
+763.50/s (n=234464)
softref: 10 wallclock secs (10.39 usr + 0.00 sys = 10.39 CPU) @ 17
+753.61/s (n=184460)
use Benchmark;
foreach (1..10) {
$hash{$_} = 'x';
$array[$_] = 'x';
${"var_$_"} = 'x';
}
sub hash { $hash{$_} = 'hash!' foreach 1..10 }
sub array { $array[$_] = 'array!' foreach 1..10 }
sub softref { ${"var_$_"} = 'ref!' foreach 1..10 }
timethese(-10, {
hash => \&hash,
array => \&array,
softref => \&softref,
});
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, details, 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, summary, 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.