[Pharo-project] Stack should be reimplemented with Array

jaayer jaayer at zoho.com
Thu Oct 14 13:43:11 EDT 2010

There was a post on this list back in August complaining about Stack inheriting from LinkedList. There was some discussion, but apparently no resolution, as Stack still inherits from LinkedList in the Pharo 1.2 Core Image I just downloaded. Rather than reimplementing it to forward to a contained LinkedList, I think it should use an Array internally like OrderedCollection does. An Array-based implementation of Stack would be faster than one based on LinkedList due to the basic stack operations (push, pop and top) being able to rely more on primitives. This assumes that you know roughly how a big a stack you need; if you don't, reallocating the array and copying its contents over and over again will cost you, but this is an exceptional case;-- most stacks are small and when they aren't, the programmer usually has enough information to select a reasonable stack size.

Enclosed is a fileout of an Array-based Stack implementation. It trounces the LinkedList-based implementation easily, but more interestingly, it performs better than an OrderedCollection when used like a stack:

Pushing is roughly ~30% faster:
r1 :=[100000 timesRepeat: [
		s := Stack new.
		10 timesRepeat: [s push: #foo]]] timeToRun.
r2 := [100000 timesRepeat: [
		oc := OrderedCollection new.
		10 timesRepeat: [oc addLast: #foo]]] timeToRun.
100 - ((r1 / r2) asFloat * 100).

as is pushing + popping:
r3 := [100000 timesRepeat: [
		s := Stack new.
		10 timesRepeat: [s push: #foo].
		10 timesRepeat: [s pop]]] timeToRun.
r4 := [100000 timesRepeat: [
		oc := OrderedCollection new.
		10 timesRepeat: [oc addLast: #foo].
		10 timesRepeat: [oc removeLast]]] timeToRun.
100 - ((r3 / r4) asFloat * 100).
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Stack.st
Type: application/octet-stream
Size: 2708 bytes
Desc: not available
URL: <http://lists.pharo.org/pipermail/pharo-dev_lists.pharo.org/attachments/20101014/e210f9eb/attachment.st>

More information about the Pharo-dev mailing list