in reply to Re^3: how to avoid nested looping?
in thread how to avoid nested looping?
Note that the differences between 'map1' and 'map3' and between 'map2' and 'map4' are smaller than the differences between 'for1' and 'for3' and the difference between 'for2' and 'for3'. And that the non-optimized fors ('for1' and 'for3') are somewhat faster than the equivalent maps ('map1' and 'map3'). Now, if you do that 101 times, I'm surprised the difference is only 75%.use strict; use warnings; use Benchmark 'cmpthese'; my $nums1 = join(",", 1..100); my $nums2 = "1..100"; cmpthese(-1, { for1 => "my \$sum=0; foreach ($nums1) {\$sum++}", for2 => "my \$sum=0; foreach ($nums2) {\$sum++}", for3 => "my \$sum=0; \$sum++ foreach ($nums1)", for4 => "my \$sum=0; \$sum++ foreach ($nums2)", map1 => "my \$sum=0; map {\$sum++} $nums1", map2 => "my \$sum=0; map {\$sum++} $nums2", map3 => "my \$sum=0; map \$sum++, $nums1", map4 => "my \$sum=0; map \$sum++, $nums2", }); __END__ Rate map1 map3 map2 map4 for1 for3 for2 for4 map1 33185/s -- -3% -5% -5% -9% -17% -25% -34% map3 34296/s 3% -- -1% -2% -6% -15% -22% -32% map2 34795/s 5% 1% -- -0% -5% -13% -21% -31% map4 34909/s 5% 2% 0% -- -5% -13% -21% -31% for1 36571/s 10% 7% 5% 5% -- -9% -17% -27% for3 40193/s 21% 17% 16% 15% 10% -- -9% -20% for2 43997/s 33% 28% 26% 26% 20% 9% -- -12% for4 50243/s 51% 46% 44% 44% 37% 25% 14% --
Perhaps the most interesting number in the above table is the 51% in the lower left corner. It means that if you compare the fastest foreach (expression form, optimized range), and pit that against the slowest map (block form, no range), and have a very minimal body, thus giving the loop overhead a significant weight, your gain is still only about 50%.
|
|---|