Sub topic 11
Choosing an implementation by cost
This chapter assumes you know Big-O notation, Python lists and references, and the Stack, ListStack, and LinkedStack classes from the earlier chapters. Here you compare the two implementations by cost and pick one without touching client code.
Same behavior, different cost
ListStack and LinkedStack pass the same behavior check. They differ in what each operation costs. The specification says nothing about cost, so cost is a separate criterion for choosing between correct implementations.
| Operation | ListStack | LinkedStack |
|---|---|---|
| push | O(1) amortized | O(1) |
| pop | O(1) | O(1) |
| peek | O(1) | O(1) |
| is_empty | O(1) | O(1) |
| Memory per item | One reference in a contiguous array | One node object with a value and a link |
Amortized means the average over many pushes. Most pushes write into spare space. Occasionally the list runs out of room and Python copies it to a larger block, and that one push costs O(n). Spread across all pushes, the average stays constant.
Big-O hides constant factors. Both stacks are O(1) per operation, but LinkedStack allocates a new object on every push. ListStack usually runs faster in practice and uses less memory per item.
Measuring instead of guessing
You can time both implementations through the shared interface. The helper below uses only push and pop, so it works with any Stack.
import time
def time_pushes_and_pops(make_stack, n):
s = make_stack()
start = time.perf_counter()
for i in range(n):
s.push(i)
while not s.is_empty():
s.pop()
return time.perf_counter() - start
for make_stack in (ListStack, LinkedStack):
elapsed = time_pushes_and_pops(make_stack, 200_000)
print(make_stack.__name__, round(elapsed, 3), "seconds")Exact numbers depend on your machine. On most machines ListStack finishes first. Treat the result as evidence for your workload, not as a general rule.
What to weigh
Pick by the needs of your program, not by the implementation that sounds more sophisticated.
- Typical speed. Contiguous storage tends to be faster in practice because of fewer allocations and better memory locality.
- Worst-case latency. If a single slow push is unacceptable, such as in a real-time loop, the occasional O(n) resize in
ListStackmatters.LinkedStackhas no resize, so each push costs the same. - Memory. A node holds a value plus a link, so
LinkedStackuses more memory per item. - Simplicity. Choose the representation that is easier to get right and keep correct.
If none of these differences matter for your program, choose the simpler one and move on.
Switching costs nothing for clients
Because clients depend only on the Stack interface, a cost-driven switch changes one line, the place where the stack is created.
def make_default_stack():
return ListStack() # change to LinkedStack() if profiling says so
def reverse_all(batches):
return [reverse(batch, make_default_stack()) for batch in batches]
print(reverse_all([[1, 2, 3], ["a", "b"]]))
# [[3, 2, 1], ['b', 'a']]Nothing in reverse_all or reverse changes if you swap the implementation. That is the benefit of the ADT boundary. You can start with the simplest correct implementation and replace it later, only if measurement shows a problem.
Common mistakes
- Choosing by Big-O alone when the operations have the same complexity class. Constant factors can still decide.
- Optimizing before measuring. A faster stack rarely matters if the program spends its time elsewhere.
- Changing the implementation and skipping the behavior check. A cost-motivated change can still introduce bugs.
Exercise
Both ListStack and LinkedStack have O(1) push. Name one reason you might still choose LinkedStack, and one reason you might choose ListStack.
Show answer
Choose LinkedStack when you need every push to cost the same, because it never resizes an underlying array. Choose ListStack when you want lower memory use per item and usually faster operations from contiguous storage.
Exercise
You replace ListStack with LinkedStack in makedefaultstack for speed reasons. Which code must you change in reverse_all and reverse, and what should you run afterward?
Show answer
None of it. Both depend only on the Stack interface. Afterward, run checkstackbehavior on the new implementation, and time it again to confirm the change helped.