SimpleBoxes.e | merging hashs in perl

merging hashs in perl

I've investigated the merge of hashs (associative arrays) in perl. Then I've recorded it as a note for myself.

Probably the following code is the most intuitive.

%hash = (%hash, %addition);

To add %addition into %hash.

my %hash = (
  'key1' => 'value1',
  'key2' => 'value2',
);
my %addition = (
  'key3' => 'value3',
  'key4' => 'value4',
  'key1' => 'override1',
);
%hash = (%hash, %addition);

When the above code is run, %hash will be as follows:

  'key1' => 'override1',
  'key2' => 'value2',
  'key3' => 'value3',
  'key4' => 'value4',

A value of key1 is overwritten.

We can use while or foreach loop to merge hashes.

The following code uses while and each:

while (my($key,$val) = each (%addition))
{
  $hash{$key} = $val;
}

The following code uses foreach and keys:

foreach my $key (keys %addition)
{
  $hash{$key} = $addition{$key};
}

We can also use map to merge hashes such as:

map { $hash{$_} = $addition{$_} } keys %addition;

At last, we can use slice. Using "slice" is like a hack, I'm not familiar with this way.

@hash { keys %addition } = values %addition;

We should use @hash instead %hash to use slice.

Using hash reference, we can code as follows:

# normal merge
$hash = {%{$hash}, %addition};
# use while
while (my($key,$val) = each (%addition))
{
  $hash->{$key} = $val;
}
# use foreach
foreach my $key (keys %addition)
{
  $hash->{$key} = $addition{$key};
}
# use map
map { $hash->{$_} = $addition{$_} } keys %addition;
# use slice
@{$hash} { keys %addition } = values %addition;

I've taken benchmarks for those ways. The code for the benchmarks is in sequel part of this article.

foreach:  4 wallclock secs ( 4.17 usr +  0.00 sys =  4.17 CPU) @ 119904.08/s (n=500000)
    map:  5 wallclock secs ( 3.96 usr +  0.00 sys =  3.96 CPU) @ 126262.63/s (n=500000)
  merge:  7 wallclock secs ( 6.66 usr +  0.01 sys =  6.67 CPU) @ 74962.52/s (n=500000)
  slice:  5 wallclock secs ( 4.32 usr +  0.01 sys =  4.33 CPU) @ 115473.44/s (n=500000)
  while:  5 wallclock secs ( 4.35 usr +  0.01 sys =  4.36 CPU) @ 114678.90/s (n=500000)

I prefer "map" for merging hashes because "map" looks faster than others pretty stably.

Sometimes "slice" recorded the fastest however I could not find the condition.

:: Tokyo Disney Resort >>