Free degree-level programming lessons for careful independent study.

Degree Level Programmes · Programming 2 · Lesson 9

Time, Space and Speed Trade-offs

Compare simple design choices using execution time, memory use, readability and scale.

Lesson Overview

Compare simple design choices using execution time, memory use, readability and scale.

Portfolio focus: Compare two lookup approaches.

ConceptEfficiency
Run fileTimeSpaceSpeedTradeoffsDemo.java
BaselineList contains Ada? true Ada mark by key: 72
Evidence3 tasks

Starter: think before typing

Before running this efficiency example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `List contains Ada? true Ada mark by key: 72`; predict how the focus line helps produce that evidence.

Learning Objectives

  • Explain time and space as practical trade-offs.
  • Compare linear search with map lookup.
  • Recognise when readability is more valuable than micro-optimisation.
  • Use simple measurements carefully.

Learning Outcomes

  • By the end of the lesson, you can explain time and space as practical trade-offs.
  • By the end of the lesson, you can compare linear search with map lookup.
  • By the end of the lesson, you can recognise when readability is more valuable than micro-optimisation.
  • By the end of the lesson, you can use simple measurements carefully.

Why this idea exists

Efficiency is about trade-offs, not simply making everything faster. Computer science has long studied how algorithms use time and memory because the right design can change what is feasible.

Hardware has become faster, but data and expectations have grown too. A solution that is fine for ten records may fail for ten million, while a highly optimised solution may be harder to read and maintain.

Degree-level judgement means matching the optimisation to the evidence. Measure when useful, reason about scale, and explain why the chosen approach is appropriate for the problem.

Deep dive

Mechanism in this example

The important mechanism is visible around `System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.

Design pressure

Degree-level judgement means matching the optimisation to the evidence. Measure when useful, reason about scale, and explain why the chosen approach is appropriate for the problem.

Failure mode to watch

For Time, Space and Speed Trade-offs, deliberately disturb the assumption behind `System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the efficiency design.

Extension step

Extend the example by doing this: Estimate which scales better. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.

Portfolio standard

The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: write a note explaining the chosen trade-off.

Lesson visual

A photographic stopwatch, memory chips and code listings comparing list search with map lookup.
A photographic stopwatch, memory chips and code listings comparing list search with map lookup.Download visual

Type this and run it

Create TimeSpaceSpeedTradeoffsDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TimeSpaceSpeedTradeoffsDemo {
  public static void main(String[] args) {
    List<String> names = List.of("Ada", "Grace", "Alan");
    Map<String, Integer> marksByStudent = new HashMap<>();
    marksByStudent.put("Ada", 72);
    System.out.println("List contains Ada? " + names.contains("Ada"));
    System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));
  }
}

Build and run it with:

javac TimeSpaceSpeedTradeoffsDemo.java && java TimeSpaceSpeedTradeoffsDemo

Expected baseline: List contains Ada? true Ada mark by key: 72

Run the code in your browser

Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates efficiency and compare the new behaviour with the reference output.

Line-by-line explanation

Read the code as a sequence of responsibilities. The focus line for this lesson is System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));; the surrounding lines prepare it, use its result or make the behaviour observable.

import java.util.HashMap;

In Time, Space and Speed Trade-offs, this imports HashMap: a map implementation for key-based lookup.

import java.util.List;

In Time, Space and Speed Trade-offs, this imports List: the ordered collection type used to hold several values.

import java.util.Map;

In Time, Space and Speed Trade-offs, this imports Map: the key-value collection interface.

public class TimeSpaceSpeedTradeoffsDemo {

This names the runnable class for the Time, Space and Speed Trade-offs example, giving the compiler and JVM one clear unit to build.

public static void main(String[] args) {

This is the program entry point. In Time, Space and Speed Trade-offs, it keeps the demonstration of efficiency in one traceable starting script.

List<String> names = List.of("Ada", "Grace", "Alan");

This creates a small fixed list of values for Time, Space and Speed Trade-offs. In this line, the list is the data source being passed into another operation.

Map<String, Integer> marksByStudent = new HashMap<>();

This creates a collection object in Time, Space and Speed Trade-offs, choosing the data structure before marksByStudent is stored or looked up.

marksByStudent.put("Ada", 72);

This calls marksByStudent.put with "Ada", 72 in Time, Space and Speed Trade-offs. Look for the method definition to see what work actually happens.

System.out.println("List contains Ada? " + names.contains("Ada"));

This prints "List contains Ada? " + names.contains("Ada") as the observable evidence for Time, Space and Speed Trade-offs. The output lets the learner check whether the efficiency idea behaved as predicted.

System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));

This prints "Ada mark by key: " + marksByStudent.get("Ada") as the observable evidence for Time, Space and Speed Trade-offs. The output lets the learner check whether the efficiency idea behaved as predicted.

}

This closes the innermost Time, Space and Speed Trade-offs block, so the immediately preceding method, branch or loop has finished.

}

This closes the outer Time, Space and Speed Trade-offs structure, returning the reader to the surrounding class or file.

Worked example

From code to explanation

Problem: Use Time, Space and Speed Trade-offs to complete a small portfolio-quality step: Compare two lookup approaches.

Method: Locate the line `System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.

Reveal worked answer

The checked run should produce `List contains Ada? true Ada mark by key: 72`. A strong answer links the result back to efficiency: what was created, selected, stored, called or protected, and why that matters for the portfolio task.

Trace the program

Before: Before the key operation, identify the relevant value, object, branch or resource that the efficiency concept depends on.

During: Trace `System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));` as the Time, Space and Speed Trade-offs example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.

After: Compare the run with the expected evidence: `List contains Ada? true Ada mark by key: 72`.

Change: Now estimate which scales better, run again, and explain the smallest reason the behaviour changed.

Common misconception

A common mistake in time, space and speed trade-offs is treating the example as a finished answer. For efficiency, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?

Quick checks

1. In this Time, Space and Speed Trade-offs example, what is the best reason to focus on `System.out.println("Ada mark by key: " + marksByStudent.get("Ada"));`?

2. Which evidence is strongest after you edit and rerun this example?

How to study this lesson

For Time, Space and Speed Trade-offs, predict how efficiency changes the run before you press Run.

Use the first portfolio task as your main edit: Compare two lookup approaches.

Use the second task as your variation: Estimate which scales better.

Finish with evidence, not a diary entry: Write a note explaining the chosen trade-off.

Portfolio Practice

  1. Compare two lookup approaches.
  2. Estimate which scales better.
  3. Write a note explaining the chosen trade-off.

Final self-check

Can you explain the key operation?

Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output List contains Ada? true Ada mark by key: 72 appears.

Can you justify the portfolio evidence?

Your evidence should include the original run, one edited run, and a short note explaining how the edit affected efficiency.

Study route

Practise efficiency by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.

Next, move into Interfaces and Higher-Level Abstractions and carry forward one improvement from this lesson into the next program.