In a recent discussion about dynamic variables (${'foo'.$i} in the activeperl@listserv.activestate.com mailinglist someone said
dynamic scalars can sometimes be a better solution than hashes (in term of speed and memory usage) if you don't need to be able to retrieve their names (with a key or an each statement), but only want them to be accessible when called with the proper variable name.
I thought he was wrong because package variables also live in an (almost) ordinary hash. ( Try to print join("\n", keys %main:: ),"\n";) And since this hash doesn't contain directly the scalars, but GLOBs, the memory footprint is actually bigger if you use plenty of "dynamic" variables, that if you use an ordinary hash.
But did not want to post that without support so I tried this script:
And the difference was even bigger than I expected (well especialy thanks to the fact the values were so small.) The hash solution needed 15,292KB of RAM, while the dynamic variables needed 41,380KB. (According to the Task Manager in my Win2k Server)for(my $i=0; $i < 100000; $i++) { $hash{'foo'.$i} = ''; # using a hash # ${'foo'.$i} = ''; # using dynamic variables } print "done\n"; <STDIN>;
The speed of the dynamic variables was also worse than that of the hash:
#!perl use Benchmark; my %hash; for(my $i=0; $i < 1000; $i++) { $hash{'foo'.$i} = 0; ${'foo'.$i} = 0; } sub useHash { my %hash; for(my $i=0; $i < 1000; $i++) { $hash{'foo'.$i}++; } } sub useVars { my %hash; for(my $i=0; $i < 1000; $i++) { ${'foo'.$i} ++; } } timethese 1000, { useHash => \&useHash, useVars => \&useVars, }; __END__ Benchmark: timing 1000 iterations of useHash, useVars... useHash: 3 wallclock secs ( 2.68 usr + 0.00 sys = 2.68 CPU) @ 372.58/s (n=1000) useVars: 4 wallclock secs ( 3.79 usr + 0.00 sys = 3.79 CPU) @ 264.20/s (n=1000)
So the dynamic variables are not only more dangerous, but also slower and more memory-hungry. Not that the other reasons not to use them would not be enough, but it can't hurt to (try to) destroy one more myth ;-)
Jenda
Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.
-- Rick Osborne
P.S.: Yes I know I could have used an array, but I wanted to give the dynamic variables a fair chance. :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Symbolic refs aka. dynamic variables again
by eduardo (Curate) on Apr 24, 2003 at 19:41 UTC | |
by grantm (Parson) on Apr 24, 2003 at 19:57 UTC | |
by particle (Vicar) on Apr 24, 2003 at 20:08 UTC | |
by diotalevi (Canon) on Apr 25, 2003 at 00:30 UTC | |
by perrin (Chancellor) on Apr 24, 2003 at 19:46 UTC | |
|
Re: Symbolic refs aka. dynamic variables again
by particle (Vicar) on Apr 24, 2003 at 20:13 UTC | |
by diotalevi (Canon) on Apr 25, 2003 at 02:15 UTC | |
by Jenda (Abbot) on Apr 25, 2003 at 10:18 UTC |