Your Foreach test uses map, and your Map test uses foreach. You're making me dizzy. After fixing the test names and running the test for 10 seconds, foreach was 76% faster than map:
Rate Map Foreach Map 21.9/s -- -43% Foreach 38.6/s 76% --
Foreach is faster as expected, since foreach doesn't have to build a long list like map does. Update: I wrote a foreach loop that builds an array which is later assigned to %hash. As you can see below, "Map" and "Map-like" have very similar results, as expected.
use strict; use Benchmark (); Benchmark::cmpthese(-10, { "Map" => sub { my %hash = map{$_=>1} (1..10000); }, "Foreach" => sub { my %hash; $hash{$_} = 1 foreach (1..10000); }, "Map-like" => sub { my @a; push(@a, $_, 1) foreach (1..10000); my %hash = @a; }, }) __END__ Rate Map-like Map Foreach Map-like 21.5/s -- -1% -44% Map 21.8/s 1% -- -43% Foreach 38.6/s 80% 77% --
In reply to Re: performance of map vs. foreach
by ikegami
in thread performance of map vs. foreach
by johnnywang
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |