use Benchmark;
$a = shift;
$b = shift;
print "A = $a\tB = $b\n";
$hash{$_} = $_ for (1..$b);
@array[$_] = $_ for (1..$b);
sub doSubR { ${$_[0]} = ${$_[0]}}
sub doSubV { return $_[0] }
timethese ( $a, {
'1 Nothing ' => 'for (1..$b) { $trash = $_ };',
'2 Mult ' => 'for (1..$b) { $trash = $_ * $_ };',
'3 Array ' => 'for (1..$b) { $trash = $array[$_] };',
'4 Hash ' => 'for (1..$b) { $trash = $hash{"$_"} };',
'5 Sub (Ref)' => 'for (1..$b) { doSubR(\$_); $trash = $_ };',
'6 Sub (Val)' => 'for (1..$b) { $trash = doSubV($_) };',
});
####
[lexicon]$ perl bench.pl 10 1000000
A = 10 B = 1000000
Benchmark: timing 10 iterations of 1 Nothing , 2 Square , 3 Array , 4 Hash , 5 Sub (Ref), 6 Sub (Val)...
1 Nothing : 35 wallclock secs (29.99 usr + 0.10 sys = 30.09 CPU)
2 Square : 58 wallclock secs (48.79 usr + 0.23 sys = 49.02 CPU)
3 Array : 63 wallclock secs (54.49 usr + 0.20 sys = 54.69 CPU)
4 Hash : 184 wallclock secs (156.99 usr + 0.60 sys = 157.59 CPU)
5 Sub (Ref): 388 wallclock secs (327.87 usr + 1.30 sys = 329.17 CPU)
6 Sub (Val): 312 wallclock secs (266.54 usr + 1.02 sys = 267.56 CPU)
##
##
Function Time(S) Relative
Mult: 19 01.00
Array: 24 01.25
Hash: 127 06.68
Sub (R): 299 15.70
Sub (V): 237 12.47