Skip to content

Instantly share code, notes, and snippets.

@cowens
Created July 22, 2009 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowens/151792 to your computer and use it in GitHub Desktop.
Save cowens/151792 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark;
my %h = map { $_ => $_ } 1 .. 10;
my %subs = (
for => sub {
my @a;
push @a, "$_ $h{$_}\n" for keys %h;
return @a
},
while => sub {
my @a;
while (my ($k, $v) = each %h) {
push @a, "$k $v\n"
};
return @a;
}
);
for my $sub (keys %subs) {
print "$sub => ", $subs{$sub}->(), "\n";
}
for my $n (10, 100, 1_000, 10_000) {
%h = map { $_ => $_ } 1 .. $n;
print "\nfor a hash with $n keys:\n";
Benchmark::cmpthese -1, \%subs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment