Sub topic 11
Choosing an implementation by cost
You have two correct stacks, ListStack and LinkedStack. Both keep every promise in the Stack specification, so a client cannot tell them apart by behavior. This chapter covers what separates them: how much time and memory each one uses, and how to pick between them without touching client code.
This chapter assumes you know Big-O notation, Python lists, and the Stack interface from the earlier chapters.
Cost is not part of the behavioral specification
A behavioral specification says what each operation returns, which errors it raises, and how operations relate. It usually says nothing about speed. Two implementations can both be correct and still differ by orders of magnitude in running time.
That gap is the reason to treat cost as a separate decision. Correctness decides whether an implementation is allowed. Cost decides which allowed implementation you prefer. Because clients depend only on the interface, you can make that choice late and change it later.
Comparing the two stacks
The table lists the cost of each operation for the two implementations from earlier in this tutorial.
| Operation | `ListStack` | `LinkedStack` |
|---|---|---|
| `push` | O(1) amortized, O(n) worst case | O(1) worst case |
| `pop` | O(1) | O(1) |
| `peek` | O(1) | O(1) |
| `is_empty` | O(1) | O(1) |
| Memory per item | One pointer slot, plus unused spare capacity | One node object holding a value and a pointer |
Every operation is O(1) in both, so Big-O alone does not separate them. The differences are in the details.
Amortized versus worst-case cost
A Python list keeps spare capacity. Most append calls write into a free slot. Occasionally the list is full, so it allocates a larger block and copies every item, which costs O(n). The list grows its capacity geometrically, so the copies are rare enough that the average cost per push over a long sequence is constant. That average is the amortized cost.
Amortized O(1) does not mean every call is fast. A single push can be slow. For a batch job that only cares about total time, this does not matter. For something with a strict per-call deadline, such as a real-time control loop, it can. LinkedStack.push allocates one small node and never copies existing items, so its worst case is also O(1).
Constant factors and memory
Big-O hides constants. In CPython, a list stores items in one contiguous block, and append and pop run in C. LinkedStack creates a Python object per item and runs Python-level code for each operation. In practice ListStack is usually faster and uses less memory per item, even though the Big-O rows match.
The linked version has one advantage in memory behavior: it never holds a large block of unused capacity, and it never needs one large contiguous allocation.
An implementation that is correct but expensive
Correctness does not guarantee reasonable cost. Suppose someone stores the top of the stack at the front of a list:
class FrontListStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.insert(0, item) # shifts every existing item
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop(0) # shifts every remaining item
def peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[0]
def is_empty(self):
return not self._itemsThis passes every behavioral test. push and pop are O(n) because each one moves all the other items. Filling and then emptying the stack with n items costs O(n²) in total. This is why the representation decision, which end of the list is the top, matters even when the interface is identical.
Measuring instead of guessing
Big-O tells you how cost grows. Measurement tells you the actual cost on your machine and workload. This script is self-contained and times a fill-then-empty workload for three implementations at three sizes:
import timeit
class ListStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def is_empty(self):
return not self._items
class FrontListStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.insert(0, item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop(0)
def is_empty(self):
return not self._items
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
class LinkedStack:
def __init__(self):
self._head = None
def push(self, item):
self._head = _Node(item, self._head)
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
value = self._head.value
self._head = self._head.next
return value
def is_empty(self):
return self._head is None
def workload(make_stack, n):
s = make_stack()
for i in range(n):
s.push(i)
while not s.is_empty():
s.pop()
for make_stack in (ListStack, LinkedStack, FrontListStack):
for n in (10_000, 20_000, 40_000):
seconds = timeit.timeit(lambda: workload(make_stack, n), number=3)
print(f"{make_stack.__name__:15} n={n:6} {seconds:.4f}s")Exact times depend on your machine, so do not compare them with anyone else's. Look at the pattern instead. For ListStack and LinkedStack, doubling n should roughly double the time. For FrontListStack, doubling n should roughly quadruple it, which is the O(n²) growth showing up. Often FrontListStack still looks fine at small sizes because moving a short block of memory is cheap, and the cost only becomes visible as n grows.
Swapping without touching clients
Because clients use only push, pop, peek, and is_empty, changing the implementation is a one-line change at the point where the stack is created:
def evaluate(tokens, make_stack):
stack = make_stack()
for token in tokens:
if token in "+-*":
right = stack.pop()
left = stack.pop()
if token == "+":
stack.push(left + right)
elif token == "-":
stack.push(left - right)
else:
stack.push(left * right)
else:
stack.push(int(token))
return stack.pop()
class ListStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
print(evaluate(["2", "3", "4", "*", "+"], ListStack)) # 14evaluate takes the stack factory as a parameter, so the choice lives in the caller. You could pass LinkedStack here instead and the function would not change. That is the practical payoff of the interface: the cost decision stays reversible.
A decision process
The diagram shows the order of questions that works well in practice.
In short:
- Rule out incorrect implementations first. Cost comparisons between a correct and an incorrect stack are meaningless.
- Decide whether cost matters at all. For a stack holding a few dozen items, it does not, and the simplest code wins.
- Measure with a realistic workload and data sizes.
- Choose the cheapest implementation that meets the requirement, then rerun the specification tests against it.
Common mistakes
- Treating equal Big-O as equal cost. Constant factors, allocation, and memory layout can make one O(1) implementation several times faster than another.
- Optimizing before measuring. Picking
LinkedStackbecause "linked lists avoid resizing" often produces slower code in Python. - Ignoring worst-case cost. Amortized O(1) is fine for throughput and risky for latency limits.
- Putting cost promises into the interface by accident. If clients start assuming
pushis always instant, a later swap can break them even though behavior is unchanged. If cost matters to clients, document it in the specification on purpose. - Skipping retesting after a swap. Run the same behavior checks against the new implementation before shipping it.
Exercise
A team has a stack of undo actions in a text editor. Pushes happen on every keystroke, and each push must finish within a few milliseconds. Memory is plentiful. Which of ListStack and LinkedStack is the safer choice if an occasional slow push would be visible to the user, and what would you do before committing to it?
Show answer
LinkedStack has a worst-case O(1) push, so no single push triggers a copy of all items. ListStack has amortized O(1) push but an occasional O(n) resize. Before committing, measure the maximum single-push time and the typical time on a realistic number of undo actions, because the resize may be too rare or too fast to matter. Then run the specification tests against the chosen implementation. If ListStack meets the deadline, its lower constant cost and memory use make it the better choice, and the client code does not change either way.