in reply to Map Vs Foreach
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Map Vs Foreach
by perlCrazy (Monk) on Nov 26, 2009 at 09:35 UTC | |
Also I was under impression that map is actually faster than foreach, but my result is different ! and output of code : Time taken by foreach loop was 9 wallclock secs ( 8.22 usr 0.32 sys + 0.00 cusr 0.00 csys = 8.54 CPU) seconds Time taken by map block was 15 wallclock secs (14.88 usr 0.72 sys + 0.00 cusr 0.00 csys = 15.60 CPU) seconds | [reply] [d/l] |
by cdarke (Prior) on Nov 26, 2009 at 09:59 UTC | |
I was unhappy about your benchmark, since the two types of code did not appear to be the same: in particular seemed suspect to me. Also the order of memory allocation can affect benchmarks. When I ran the supplied code the foreach loop worked fine (5 seconds on my machine) but the map gave Out of memory!. So I rewrote each part to be a subroutine, and tided the map so it looked like this: I can't say if that was faster, because it still gives Out of memory! Must be something to do with a temporary list (5.10.1 on Windows). Reducing the size of @data by a factor of 10 gives map taking around twice as long, and each taking under a second. | [reply] [d/l] [select] |
by Ratazong (Monsignor) on Nov 26, 2009 at 10:24 UTC | |
resulted in the following measurement-output:
Time taken by foreach loop was 2 wallclock secs ( 2.27 usr 0.03 sys + 0.00 cusr 0.00 csys = 2.30 CPU) seconds | [reply] [d/l] [select] |
by ikegami (Patriarch) on Nov 26, 2009 at 16:16 UTC | |
by Marshall (Canon) on Nov 26, 2009 at 10:39 UTC | |
is not the way to use map to generate a new list of @data with values of +2. here is the right way... map{} returns the value of the last statement. I put this $bullshit statement in there to "throw you off"...it means absolutely nothing! Use the power of the language.
my @dataPlus2 = map { $_ + 2 }@data; map{} is best used for a line or two translations. I wouldn't normally do it this way, this is just to show you that it is possible:
| [reply] [d/l] [select] |
by JadeNB (Chaplain) on Nov 28, 2009 at 05:29 UTC | |
I wouldn't normally do it this way, this is just to show you that it is possible: Possible, but, as you doubtless know, not desirable: This version makes two passes over the list—or, rather, one pass over the list, then one pass over its transformation—whereas does the same thing in only one pass. I do take issue, though, with the statement that map is best for 1- or 2-line transformations. I think that's a readability opinion, and these are always subjective. It also might lead some into using map for a short transformation to which it's not suited. I think a less subjective guideline, and one that might be more useful when deciding which to use, is:
| [reply] [d/l] [select] |