![]() |
|
good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
To push and pop or not to push and pop?by GrandFather (Saint) |
on Nov 05, 2005 at 22:24 UTC ( #506033=perlmeditation: print w/replies, xml ) | Need Help?? |
It's pretty easy just to assume that "it" is so. "It" may of course be any of many things, but in this case "it" is that "push and pop are obviously faster than unshift and shift". Clearly push and pop work at the growable end of the array so obviously there is an efficiency advantage. I was curious to see how much faster the push/pop pair were than the unshift/shift pair. The answer may come as something of a surprise - it did to me!
There are two big surprises here, at least for me:
Every now and then a problem comes up that could be solved using either of the stack pairs. In the past I would always choose push/pop. Now I'm happier thinking about the best expression of the problem and not being distracted by assumed efficiency issues. Even more interesting though is the queue result which was quite unexpected. Note though that the fastest pair was push/shift. After a little contemplation this is not quite so surprising. After all shift is often used to pull arguments out of the list passed to a sub and push is often used to tack elements on to the end of a list. These are used much more than pop and unshift so it makes sense that there is some optimisation for them. Obvious after the benchmark anyway. :) Perl is Huffman encoded by design.
Back to
Meditations
|
|