Сухой27 Сухой27 - 6 months ago 20
Perl Question

keys vs values performance

I would like to know theoretical background of hash values performing better than keys, and whether perldoc covers this topic.

use strict;
use warnings;
use Benchmark qw(:all);

my %hash = 1 .. 30_000;

cmpthese(-3, {
values => sub {
for my $v (values %hash) { }

},
keys => sub {
for my $v (keys %hash) { }
},
avalues => sub {
for my $v (@{[ values %hash ]}) { }
},
akeys => sub {
for my $v (@{[ keys %hash ]}) { }
},
});

__DATA__
Rate akeys keys avalues values
akeys 196/s -- -33% -56% -71%
keys 294/s 50% -- -35% -57%
avalues 451/s 130% 54% -- -33%
values 677/s 245% 131% 50% --


perl is 5.20.0

Answer

The keys aren't stored in the hash as scalar. A string scalar must therefore be created for each key returned by keys.

for (keys(%h)) {
   $_ = uc($_);  # Has no effect on the hash.
}

On the other hand, the values are stored as scalars in the hash, and those very scalars are returned by values. Nothing copied but a pointer.

for (values(%h)) {
   $_ = uc($_);  # Effects the hash.
}
Comments