|Just another Perl shrine|
Re (tilly) 1: Efficient Looping Constructsby tilly (Archbishop)
|on Sep 29, 2001 at 07:41 UTC||Need Help??|
While I agree with what you want people to do, I think you have hit on the single worst possible reason to do it.
Namely code tuning.
There are far better reasons that you can and should point out. For instance one of the most common errors in C is a fencepost error. If you use C-style loops, it will be as common in Perl as it is in C. (In fact you have a fencepost error in your benchmark code.) If you loop using Perlish foreach loops, this error practically vanishes.
So by using foreach style looping you can kill one of your most common bugs. Not bad.
As for the abuses of map and grep, yes, they waste time and memory. However they also make your code less clear. They do more than a foreach loop does, and therefore you have more to think about when you run across one. That for me is a bigger deal than code tuning.
Oh, and a note. People say that they use map in golf because it is shorter. Wrong.
Even for golfing purposes, gratuitous abuse of map and grep is usually misguided.
Now if you can write code using a hash lookup instead of a grep, well that is not just code tuning, that is an algorithmic improvement. When you start talking algorithmic improvements, you get huge performance increases. But even so a hash lookup is clearer. So even if the program will run fast enough either way, I would use the hash lookup for clarity.
And everything that I just said about writing using Perl's syntactic sugar is sufficient for me to use it, regardless of whether it was faster. And it is important to think that way. Because if you talk to people about how fast constructs are, and teach them to think at that level, before you know it they will miss the forest for the trees.
Why would any performance oriented person use a hash instead of an array for a structure? Array access uses less memory and runs faster! But a hash is self documenting. It is faster to debug. You make fewer mistakes. What it costs in computer time and energy is more than made up for in human time.
I want people to use hashes. I want that because I don't want to waste my time wading through buggy and unreadable positionally based logic. And it doesn't happen until programmers understand that there is such a thing as "fast enough" and from then on their time is worth more than the computer's time. (Besides which, worrying about maintainability gives you more leisure to profile and find bigger speed increases later. Worrying about speed at every step is likely to result in a slower program in the end.)