Benchmarking foreach versus map in perl

Benchmarking foreach versus map in perl


The Learning perl and Intermediate perl books say that map() is better then a foreach, lets see by how much!
  • foreach my $line (@array){               |           map {print $_ } @array;
       print $line                           |
    }                                        |
    
  • As you can see, the map is simplier and dosn't require us to come up with a variable name, nice!
    I quickly made this program lets see the results! I printed and redirected to /dev/null since printing to stdout would be too slow and messy!
  • perl benchmark_looping_techniques.pl 2>/dev/null
    for method:     (22.62 usr +  8.79 sys = 31.41 CPU) @  3.28/s (n=103)
    foreach method: (22.61 usr +  8.91 sys = 31.52 CPU) @  3.27/s (n=103)
    map method:     (22.98 usr +  8.48 sys = 31.46 CPU) @  3.18/s (n=100)
    
  • Well, that kinda sucks, I was hoping map would be faster....Maybe if i rewrite the program without the print?
  • for method:     (31.36 usr +  0.01 sys = 31.37 CPU) @ 17.60/s (n=552)
    foreach method: (31.55 usr +  0.01 sys = 31.56 CPU) @ 17.43/s (n=550)
    map method:     (31.38 usr +  0.01 sys = 31.39 CPU) @ 14.18/s (n=445)
    
  • map is faster, but its not really DOING anything here! Lets rewrite the program to no longer print every line
  • for_method:     (31.47 usr +  0.02 sys = 31.49 CPU) @ 10.61/s (n=334)
    foreach_method: (31.47 usr +  0.01 sys = 31.48 CPU) @ 10.61/s (n=334)
    map_method:     (30.02 usr +  0.02 sys = 30.04 CPU) @  2.96/s (n= 89)
    

  • ZOMGWTFBBQ!! map is SLOWER then the for and foreach methods....Someone please tell me my test program is faulty!


    System specs: Perl 5.8.8 Single proc, fedora 8