in reply to Hash references and efficiency

These kinds of questions are always best answered using a benchmark ;)
#!/usr/bin/perl -w use strict; use Benchmark qw(cmpthese); sub returnhashref { my %a=(); for (1 .. 1000) { $a{$_}=$_; } return \%a; } cmpthese(-3,{ 'Ref' => sub { my $a=returnhashref(); return $$a{245}}, 'newhash' => sub { my $a=returnhashref(); my %a = %$a; return +$a{245}}});
Benchmark: running Ref, newhash, each for at least 3 CPU seconds... Ref: 3 wallclock secs ( 3.24 usr + 0.01 sys = 3.25 CPU) @ 38 +1.54/s (n=1240) newhash: 3 wallclock secs ( 3.21 usr + 0.00 sys = 3.21 CPU) @ 21 +1.84/s (n=680) Rate newhash Ref newhash 212/s -- -44% Ref 382/s 80% --
So using the ref is about 50% faster in this case. Btw. the easiest way of dereferencing is using the shortcut $$a{somekey} instead of $a->{somekey}

T I M T O W T D I

Replies are listed 'Best First'.
Re: Re: Hash references and efficiency
by perrin (Chancellor) on Aug 03, 2002 at 18:16 UTC
    These kinds of questions are always best answered using a benchmark ;)

    Um, no offense, but no they aren't. This sort of question is best answered by considering code readability, and maybe memory usage. The odds that this is going to be a performance bottleneck in any real application are slim to none. Don't be a slave to Benchmark.