use Benchmark qw(timethese cmpthese countit timestr); my $hash1 = { one => 'One', two => 'One', three => 'One', four => 'One', five => 'One', }; my $hash2 = { one => 'One', four => 'One', five => 'One', }; my $hash3 = {}; for (0..1000) { $hash3->{"foo_$_"} = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } cmpthese (-2,{ forloop => sub { my $hash = {}; foreach my $foo ($hash1, $hash2, $hash3) { foreach my $key (keys %$foo) { $hash->{$key} = $foo->{$key} if ! exists $hash->{$key}; } } }, forloop2 => sub { my $hash = {}; foreach my $foo ($hash3, $hash2, $hash1) { foreach my $key (keys %$foo) { $hash->{$key} = $foo->{$key}; } } }, whileloop => sub { my $hash = {}; foreach my $foo ($hash1, $hash2, $hash3) { while (my($key, $val) = each %$foo) { $hash->{$key} = $val if ! exists $hash->{$key}; } } }, whileloop2 => sub { my $hash = {}; foreach my $foo ($hash3, $hash2, $hash1) { while (my($key, $val) = each %$foo) { $hash->{$key} = $val; } } }, slice => sub { my $hash = {}; foreach my $foo ($hash3, $hash2, $hash1) { @$hash{keys %$foo} = values %$foo; } }, merge => sub { my $hash = {%$hash3, %$hash2, %$hash1}; }, },'auto'); #### Benchmark: running forloop, forloop2, merge, slice, whileloop, whileloop2, each for at least 2 CPU seconds... forloop: 3 wallclock secs ( 2.22 usr + 0.00 sys = 2.22 CPU) @ 108.11/s (n=240) forloop2: 2 wallclock secs ( 2.09 usr + 0.01 sys = 2.10 CPU) @ 122.38/s (n=257) merge: 2 wallclock secs ( 2.10 usr + 0.00 sys = 2.10 CPU) @ 176.19/s (n=370) slice: 2 wallclock secs ( 2.14 usr + 0.00 sys = 2.14 CPU) @ 140.19/s (n=300) whileloop: 2 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 87.04/s (n=188) whileloop2: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 110.10/s (n=229) Rate whileloop forloop whileloop2 forloop2 slice merge whileloop 87.0/s -- -19% -21% -29% -38% -51% forloop 108/s 24% -- -2% -12% -23% -39% whileloop2 110/s 26% 2% -- -10% -21% -38% forloop2 122/s 41% 13% 11% -- -13% -31% slice 140/s 61% 30% 27% 15% -- -20% merge 176/s 102% 63% 60% 44% 26% --