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!
use strict; use warnings; use Benchmark qw(cmpthese); my @template = (1) x 200; cmpthese ( -10, { 'push pop', sub {pushPop ();}, 'push shift', sub {pushShift ();}, 'unshift pop', sub {unshiftPop ();}, 'unshift shift', sub {unshiftShift ();}, } ); sub pushPop { my @from = @template; my @to; for (0..100) { push @to, pop @from for @from; push @from, pop @to for @to; } } sub pushShift { my @from = @template; my @to; for (0..100) { push @to, shift @from for @from; push @from, shift @to for @to; } } sub unshiftPop { my @from = @template; my @to; for (0..100) { unshift @to, pop @from for @from; unshift @from, pop @to for @to; } } sub unshiftShift { my @from = @template; my @to; for (0..100) { unshift @to, shift @from for @from; unshift @from, shift @to for @to; } }
Rate unshift shift push pop unshift pop push +shift unshift shift 129/s -- -0% -4% + -6% push pop 129/s 0% -- -3% + -6% unshift pop 134/s 4% 3% -- + -2% push shift 137/s 6% 6% 2% + --
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. :)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: To push and pop or not to push and pop?
by rnahi (Curate) on Nov 05, 2005 at 22:34 UTC | |
Re: To push and pop or not to push and pop?
by robin (Chaplain) on Nov 05, 2005 at 23:47 UTC | |
Re: To push and pop or not to push and pop?
by Aristotle (Chancellor) on Nov 06, 2005 at 00:21 UTC | |
Re: To push and pop or not to push and pop?
by pg (Canon) on Nov 06, 2005 at 03:02 UTC |