http://www.perlmonks.org?node_id=997339


in reply to Efficiency of map vs. more verbose basic/fundamental code

Even so, I would like to understand in what ways the map version of the code above would be less efficient than the more verbose foreach loop?

You see the print part of the statement? That means the statement is going to take at least milliseconds regardless of what comes after it, so efficiency -- in terms of time -- is a red-herring. And if the hash is large, the sort is going to dominate the time required.

What the authors are probably clumsily trying to allude to it the memory (in)efficiency if the hash happens to contain a large number of keys. The one-line statement uses a lot of memory because it creates several intermediate stack based lists in order to process. If there are 1 million keys in %h, then this is what that looks like internally:

print <1e6 key/value/newline> map "$_: $h{$_}\n", <1e6 ordered keys> s +ort <1e6 unordered keys>;

You can see it can be memory hungry. Memory usage increases by 163 MB in order to execute that statement.

However, if the hash is (or could be) big enough for that to be a serious concern, then the book's alternative construction is almost as bad:

foreach $key ( <1e6 sorted items> sort <1e6 unordered items> keys %h) +{ print "$key: $h{$key}\n"; }

Here, the memory usage increases by 56 MB to process the loop. Better, but still pretty wasteful, but that cannot be avoided if you use sort.

However, you can avoid the need for spreading the single semantic operation -- display the hash pairs ordered by key -- over three lines, whilst avoiding the increased memory usage of using map, by doing it this way:

print "$_ : $h{ $_ }\n" for sort keys %h;

Clean, concise and a single line representing a single semantic operation; but then there are some books that will tell you that is "difficult (for beginners) to read".

But in the end, unless you are routinely dealing with huge datasets, all three are much of a muchness and it really comes down to what you personally prefer. Trying to guess what the next guy to come along will find most readable is a mug's game. If there are 3 ways to do something, whichever you choose you'll be wrong 2/3rds of the time.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

RIP Neil Armstrong