hashの全ての要素に何かするベンチマーク

あまり意識したことが無かった。

結果

               Rate    sub_each     sub_for sub_foreach
sub_each    17928/s          --        -27%        -27%
sub_for     24710/s         38%          --         -0%
sub_foreach 24710/s         38%          0%          --

ベンチマークコード

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(:all);
# use Data::Dumper;
my %hash;
for my $key ( "a" .. "z" ) {
$hash{$key} = int rand 100;
}
cmpthese( 100000, {
sub_for => sub {
my @array;
for my $key (keys %hash) {
push @array, { -key => $key, -val => $hash{$key} };
}
#        print Dumper(\@array);
},
sub_foreach => sub {
my @array;
foreach my $key (keys %hash) {
push @array, { -key => $key, -val => $hash{$key} };
}
#        print Dumper(\@array);
},
sub_each => sub {
my @array;
while ( my ($key, $value) =  each %hash) {
push @array, { -key => $key, -val => $value };
}
#        print Dumper(\@array);
},
});

Comments

comments powered by Disqus