Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Problems? Is your data what you think it is?
 
PerlMonks  

Re^3: When would you choose foreach instead of map?

by Anonymous Monk
on May 21, 2004 at 01:39 UTC ( [id://355188]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Re: Re: When would you choose foreach instead of map?
in thread When would you choose foreach instead of map?

I thought map() was optimized for use in void context. I'd never use map() in such a case in this as for() is much more elegant (all IMO of course). Can you explain why the map() version takes up so much memory?

  • Comment on Re^3: When would you choose foreach instead of map?

Replies are listed 'Best First'.
Re: Re^3: When would you choose foreach instead of map?
by BrowserUk (Patriarch) on May 21, 2004 at 06:28 UTC

    I believe* that the reason is nothing to do with the void context. for is optimised to treat the range operator as an iterator, by which I mean it doesn't generate a list of 1_000_000 scalars, it simply supplies the next incremented value as $_ for each iteration.

    map on the other hand doesn't have this optimisation and so a very large list is generated as the input to map. This is what (briefly) consumes the memory. For short ranges this isn't a problem, but for larger ones, it's worth avoiding.

    * I'm fairly confident that this is the case, but it is acquired knowledge rather than something I can point my finger at the sources and say "There".


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://355188]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.