in reply to Re^2: When should I use map, for?
in thread When should I use map, for?

Have you tried it? It copies -and- modifies -both-.

my @elem = ( 1..20 ); my @e = map { $_ if (s/0/./g || 1) } @elem; print join( " ", @elem ), "\n"; __END__ 1 2 3 4 5 6 7 8 9 1. 11 12 13 14 15 16 17 18 19 2.

I understand -why- you put the logical path there. Just saying s/0/./g; $_; makes more sense than the if and or.

But you are quite right. It is moot. map is still slower, though arguably clearer in the $_ + 2 case. I don't know that map {} is ever an optimization.

I would use grep to filter records, or map to preprocess going into a sort. I find that makes sense to me coding-wise. I doubt that it is better speed-wise.

addendum:

Okay, here is a case where I think map is cleaner and (slightly) faster:

my @elem = map { int rand 1000 } 1..10000; sub map_s { my @mod_sorted = sort { $a <=> $b } map { $_ % 2**6 } @elem; } sub for_s { my @a; for ( @elem ) { push @a, $_ % 2**6; } my @mod_sorted = sort { $a <=> $b } @a; } __END__ Rate for map for 15.8/s -- -4% map 16.5/s 4% --

Replies are listed 'Best First'.
Re^4: When should I use map, for?
by shemp (Deacon) on May 19, 2005 at 22:49 UTC
    In your for_s() test, the creation of the extra array may taint the results. What happens to that test when you eliminate the sort, and just create an array of the mod values?

      It does taint the results... but that's just the point. The map itself isn't faster, but it allows you to avoid the creation of the array. In that sense it doesn't taint the results... the taint is the result. If there was a way to do for_s() without the extra array, then my results would be skewed.

      So, perhaps my point, if in fact I have one... is that a pure map is likely never faster than a pure for... but that's not to say that map is never a better solution.

        Ok, i hadn't thought of it that way. I was thinking strictly about the speed of map vs. for, disregarding any other overhead that may occur as a result of how they are used.

        I am no guru when it comes to perl internals. But it seems like the map{} approach is still creating that additional array, but its just hidden away - not named. I say this because (i assume) sort will need the full array that map is creating, and that array is stored somewhere - albeit internally.

        That is something im still a bit uncertain of in regard to this.