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,
});