PBP: 072 List Generation

The Best Practice is to use map when generating a new list from an old one.  The reasoning is good, but I struggle with it anyway.  I’m getting better with effort.

I find for loops to be clear and easy to read.  I find many uses of map obtuse and difficult to read.  I have typically avoided map, and preferred to write a nice for loop instead.

It’s inefficient, and I need to get over it.

When you use for to build a new list, the list you are creating gets built one item at a time.  That often causes a sequence of memory allocations inside Perl to create each new element and insert content there.

Map knows it is creating a list and how large that list is.  It can pre-allocate the list and spend lots less time screwing around in memory allocation and more time doing your important stuff.  The looping map does is also done in heavily optimized C code inside the interpreter, instead of being processed as multiple instructions by the interpreter.  It’s going to be faster.

The secondary reason is one of context.  Map is usually used to transform one set of data into another.  When an engineer sees this, they can probably tell right away that is what is happening.  Some list of items is being transformed into some other construct.  That knowledge comes from the use of the right tool.  Seeing a for loop tells the engineer nothing more than that this list is being processed.  The fact it’s transforming is something they’ll have to learn themselves by reading the code.

Mr. Conway also says that the dense map block is easier to read, and I disagree with him there, strongly.  I find them dense, obscure little blobs of code and always have a hard time figuring out what they do and what they’ll be acting on.  But that’s my problem.

Leave a Reply