#! /usr/bin/perl
use strict;
# Build the dataset
my $iterations = 100000;
my $range = 10000;
my $num_keys = 1000;
my %hash = map { "a_" . int(rand($range)) => 0 } (0..$num_keys);
my @array = sort keys %hash;
my $cnt_array=0;
my $cnt_hash=0;
# look for random array entries
my $start = time;
for (0..$iterations) {
my $key = "a_" . int(rand($range));
for (0..@array) {
++$cnt_array if $key eq $array[$_];
}
}
my $ttl = time - $start;
print "Array search took $ttl seconds, found $cnt_array\n";
# look for random hash entries
$start = time;
for (0..$iterations) {
my $key = "a_" . int(rand($range));
++$cnt_hash if defined $hash{$key};
}
$ttl = time - $start;
print "Hash search took $ttl seconds, found $cnt_hash\n";
####
$ ./foo.pl
Array search took 33 seconds, found 9534
Hash search took 0 seconds, found 9426
####
$ ./foo.pl
Array search took 3258 seconds, found 955277
Hash search took 16 seconds, found 954543