[Israel.pm] for vs map

Yossi Itzkovich Yossi.Itzkovich at ecitele.com
Sun Jun 29 23:10:46 PDT 2008


In "Perl Best Practices" by Damian Conway  I saw a guideline  called "Use map instead of for when generating new lists from old". He explains there very well ,why map() will run faster then simple for when you generate new list from old one, for example:  map is written in c, knows the final array size from the beginning (assuming you return a scalar from the mapping code) and more.

I tried  the code below on Solaris with (perl 5.6.1 and 5.8 ) and Linux (perl 5.10) and got results that map is slower 10-40% than simple for.
Can someone explains it ?

The code:
#! /bin/env perl

use strict;
use warnings;
use Benchmark qw(cmpthese);

my @results=( 1 .. 100000);

sub simpleFor
    my @sqrt_results;
    for my $result (@results)
        push @sqrt_results, sqrt($result);

sub optimizedFor
     my @sqrt_results;

    # Preallocate as many elements as @results already has...
    $#sqrt_results = $#results;

    for my $next_sqrt_result (0..$#results) {

        $sqrt_results[$next_sqrt_result] = sqrt $results[$next_sqrt_result];

sub usingMap
    my @sqrt_results = map { sqrt $_ } @results;

cmpthese (100,
          {"simple for" => 'simpleFor();',
           "optimized for" => 'optimizedFor()',
           "with map" => 'usingMap()',

More information about the Perl mailing list