Skip to content

Instantly share code, notes, and snippets.

@logie17
Created February 3, 2013 02:14
Show Gist options
  • Save logie17/4700281 to your computer and use it in GitHub Desktop.
Save logie17/4700281 to your computer and use it in GitHub Desktop.
rekey
use Benchmark qw{cmpthese};
sub rekey1(\%\%) {
my ($key_map, $old_hash) = @_;
return
map { exists $key_map{$_}
? ( $key_map{$_} => $old_hash{$_} )
: ( $_ => $old_hash{$_} )
}
keys %old_hash;
}
sub rekey2(\%\%) {
my ($key_map, $hash) = @_;
my %new_hash = %$hash;
my @good_keys = grep { exists $hash{$_} } keys %$key_map;
return %new_hash unless @good_keys;
@new_hash{@{$key_map}{@good_keys}} = delete @new_hash{@good_keys};
return %new_hash;
}
sub rekey3(\%\%) {
my ($key_map, $hash) = @_;
my %new_hash;
while (my ($k,$v) = each %$hash) {
$new_hash{ exists $key_map{$k} ? $key_map{$k} : $k } = $v;
}
return %new_hash;
}
#sub rekey4(\%\%) {
# my ($key_map, $hash) = @_;
# my %new_hash;
#
# while (my ($k,$v) = each %$hash) {
# $new_hash{ $key_map{$k} \\ $k } = $v;
# }
#
# return %new_hash;
#}
my %new_keys = map { ( $_ => $_ * 1000 ) } (1 .. 200);
my %hash = map { ($_ => $_ + 3) } (101 .. 300);
cmpthese(10000000, {
rekey1 => sub { rekey1 %new_keys, %hash },
rekey2 => sub { rekey1 %new_keys, %hash },
rekey3 => sub { rekey1 %new_keys, %hash },
# rekey4 => sub { rekey1 %new_keys, %hash },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment