Skip to lesson

Performance and choosing well

Two programs can give the same output and still differ a thousand times in speed. The difference is almost always the collection: how many steps it needs for get, contains, add or remove as the data grows. Choosing well means knowing those step counts and matching them to what your program does most.

Big-O with real numbers

Big-O (time complexity) describes how the number of steps a program needs grows when the amount of data n grows. It ignores small fixed costs and keeps only the shape of the growth, such as O(1), O(log n) or O(n).

The program counts how many equals and compareTo calls one contains needs on a million items in an ArrayList, a HashSet and a TreeSet.

Steps per operation. ArrayList: get O(1), add O(1) on average, remove and contains O(n). LinkedList: get O(n), add O(1) at the ends, the rest O(n). HashSet and HashMap: O(1). TreeSet and TreeMap: O(log n). Sets have no get by position.

Example 1 · Counting steps instead of guessing

CountStepsDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
class Roll implements Comparable<Roll> {    static long equalsCalls = 0;    static long compareCalls = 0;    final int no;
    Roll(int no) {        this.no = no;    }
    @Override    public boolean equals(Object o) {        equalsCalls++;        return o instanceof Roll r && r.no == no;    }
    @Override    public int hashCode() {        return no;    }
    @Override    public int compareTo(Roll other) {        compareCalls++;        return Integer.compare(no, other.no);    }}
public class CountStepsDemo {    public static void main(String[] args) {        int n = 1_000_000;        List<Roll> list = new ArrayList<>();        for (int i = 1; i <= n; i++) {            list.add(new Roll(i));        }        Set<Roll> hashSet = new HashSet<>(list);        Set<Roll> treeSet = new TreeSet<>(list);        Roll target = new Roll(n);
        Roll.equalsCalls = 0;        list.contains(target);        System.out.println("ArrayList.contains: " + Roll.equalsCalls + " equals calls");
        Roll.equalsCalls = 0;        hashSet.contains(target);        System.out.println("HashSet.contains:   " + Roll.equalsCalls + " equals call");
        Roll.compareCalls = 0;        treeSet.contains(target);        System.out.println("TreeSet.contains:   " + Roll.compareCalls + " compareTo calls");    }}
Output
ArrayList.contains: 1000000 equals calls
HashSet.contains:   1 equals call
TreeSet.contains:   37 compareTo calls

What this code does

  • The counters show the work exactly, with no timing noise. The list checked all 1,000,000 rolls; the hash set went straight to one bucket and needed 1 equals call.
  • The tree needed 37 comparisons. log₂ of 1 million is about 20, and a red-black tree (the balanced tree inside TreeSet) may be up to about twice that deep. That is still O(log n).

Big-O describes how the number of steps grows when the data size n grows. It ignores small fixed costs and keeps only the shape of the growth. With n = 1,000,000 items:

  • O(1), constant: about 1 step, whatever n is. HashMap.get, ArrayList.get(i).
  • O(log n): about 20 steps, because 2 multiplied by itself 20 times passes 1 million. TreeMap.get, PriorityQueue.poll.
  • O(n), linear: about 1,000,000 steps. ArrayList.contains, LinkedList.get(i).
  • O(n log n): about 20 million steps, the cost of a good sort. O(n²): about a million million steps, which is far too slow.
Amortized O(1) means "O(1) on average over many calls". ArrayList.add is usually 1 step; once in a while the array is full and everything is copied into a bigger one, but spread over all the adds this stays a small fixed cost.

Lists and queues

Two timing tests: reading every item of an ArrayList and a LinkedList with get(i), then removing from the front of an ArrayList and an ArrayDeque.

Example 2 · Timing lists with System.nanoTime

ListTimingDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.LinkedList;import java.util.List;
public class ListTimingDemo {    static final int N = 20_000;
    static String timeMs(Runnable task) {        long best = Long.MAX_VALUE;        for (int round = 0; round < 3; round++) {            long start = System.nanoTime();            task.run();            long took = System.nanoTime() - start;            best = Math.min(best, took);        }        return String.format("%.2f", best / 1_000_000.0);    }
    static List<Integer> fill(List<Integer> list) {        for (int i = 0; i < N; i++) {            list.add(i);        }        return list;    }
    public static void main(String[] args) {        List<Integer> arrayList = fill(new ArrayList<>());        List<Integer> linkedList = fill(new LinkedList<>());
        String a = timeMs(() -> {            long sum = 0;            for (int i = 0; i < N; i++) {                sum += arrayList.get(i);            }        });        String b = timeMs(() -> {            long sum = 0;            for (int i = 0; i < N; i++) {                sum += linkedList.get(i);            }        });        System.out.println("get(i) loop   ArrayList: " + a + " ms, LinkedList: " + b + " ms");
        String c = timeMs(() -> {            List<Integer> queue = fill(new ArrayList<>());            while (!queue.isEmpty()) {                queue.remove(0);            }        });        String d = timeMs(() -> {            Deque<Integer> queue = new ArrayDeque<>();            for (int i = 0; i < N; i++) {                queue.offer(i);            }            while (!queue.isEmpty()) {                queue.poll();            }        });        System.out.println("remove front  ArrayList: " + c + " ms, ArrayDeque: " + d + " ms");    }}
Sample output
get(i) loop   ArrayList: 0.98 ms, LinkedList: 109.21 ms
remove front  ArrayList: 23.18 ms, ArrayDeque: 2.04 ms

What this code does

  • Runnable is Java's ready-made functional interface for a task with no input and no result: its one method is run(). That lets timeMs take any block of code as a lambda, like () -> { ... }, and time it.
  • Each task runs three times and the best time is kept, which removes most warm-up noise. Your numbers will differ, but the gaps will look similar.
  • get(i) on a LinkedList walks from the end every time, so the loop is O(n²). Removing from the front of an ArrayList shifts every item, while ArrayDeque.poll() is O(1).

An ArrayList keeps items side by side in an array. Reaching index i is instant, but inserting or removing near the front shifts every item after it. A LinkedList must walk node by node to reach index i, so get(i) is O(n); it is quick only at the two ends, and each node costs extra memory. In practice ArrayList wins almost everywhere, and ArrayDeque beats LinkedList as a queue or stack.

  • ArrayList: get/set O(1); add at end amortized O(1); add/remove at index O(n); contains O(n).
  • LinkedList: get(i) O(n); add or remove at either end O(1); contains O(n).
  • ArrayDeque: offer, poll, push, pop, peek at both ends O(1); no index access.
  • PriorityQueue: offer and poll O(log n); peek O(1); contains and remove(x) O(n).

Sets and maps

A HashMap, a LinkedHashMap and a TreeMap are filled with the same fares and printed. Then a railway enquiry picks the right collection for four needs.

Example 3 · HashMap, LinkedHashMap and TreeMap side by side

ThreeMapsDemo.javaJava
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.TreeMap;
public class ThreeMapsDemo {    public static void main(String[] args) {        String[] cities = {"Mumbai", "Delhi", "Chennai", "Kolkata", "Bengaluru"};        int[] fares = {1450, 1720, 1990, 2240, 1600};
        Map<String, Integer> hash = new HashMap<>();        Map<String, Integer> linked = new LinkedHashMap<>();        TreeMap<String, Integer> tree = new TreeMap<>();        for (int i = 0; i < cities.length; i++) {            hash.put(cities[i], fares[i]);            linked.put(cities[i], fares[i]);            tree.put(cities[i], fares[i]);        }
        System.out.println("HashMap:       " + hash);        System.out.println("LinkedHashMap: " + linked);        System.out.println("TreeMap:       " + tree);        System.out.println("First city A to Z: " + tree.firstKey());        System.out.println("First city after D: " + tree.ceilingKey("D"));        System.out.println("Cities before K: " + tree.headMap("K"));    }}
Output
HashMap:       {Delhi=1720, Chennai=1990, Bengaluru=1600, Kolkata=2240, Mumbai=1450}
LinkedHashMap: {Mumbai=1450, Delhi=1720, Chennai=1990, Kolkata=2240, Bengaluru=1600}
TreeMap:       {Bengaluru=1600, Chennai=1990, Delhi=1720, Kolkata=2240, Mumbai=1450}
First city A to Z: Bengaluru
First city after D: Delhi
Cities before K: {Bengaluru=1600, Chennai=1990, Delhi=1720}

What this code does

  • The HashMap order shown is what Java 17 prints for these keys, but it is not guaranteed and can change with other data or versions. LinkedHashMap keeps insertion order; TreeMap sorts the keys.
  • Only TreeMap can answer "first city", "first city from D onwards" or "cities before K", at O(log n) each.

Example 4 · Full example: one collection per need

RailwayEnquiryDemo.javaJava
import java.util.ArrayDeque;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Queue;import java.util.Set;import java.util.TreeMap;
public class RailwayEnquiryDemo {    public static void main(String[] args) {        // Need 1: find a train by number, fast -> HashMap        Map<String, String> trainsByNumber = new HashMap<>();        trainsByNumber.put("12951", "Mumbai Rajdhani");        trainsByNumber.put("12627", "Karnataka Express");        trainsByNumber.put("12301", "Howrah Rajdhani");
        // Need 2: next departure after a time, in order -> TreeMap        TreeMap<Integer, String> departures = new TreeMap<>();        departures.put(615, "12627");        departures.put(1640, "12301");        departures.put(1700, "12951");
        Set<String> bookedPnrs = new HashSet<>();
        // Need 4: waiting list, first come first served -> ArrayDeque        Queue<String> waitingList = new ArrayDeque<>();
        System.out.println("Train 12301: " + trainsByNumber.get("12301"));
        Map.Entry<Integer, String> next = departures.ceilingEntry(1200);        System.out.println("Next train after 12:00: " + next.getValue() + " at " + next.getKey());        System.out.println("Any train after 18:00? " + departures.ceilingEntry(1800));
        System.out.println("Book PNR 4521: " + bookedPnrs.add("4521"));        System.out.println("Book PNR 4521 again: " + bookedPnrs.add("4521"));
        waitingList.offer("WL1 Sunita");        waitingList.offer("WL2 Ajay");        waitingList.offer("WL3 Fiza");        System.out.println("Seat freed, confirmed: " + waitingList.poll());        System.out.println("Still waiting: " + waitingList);    }}
Output
Train 12301: Howrah Rajdhani
Next train after 12:00: 12301 at 1640
Any train after 18:00? null
Book PNR 4521: true
Book PNR 4521 again: false
Seat freed, confirmed: WL1 Sunita
Still waiting: [WL2 Ajay, WL3 Fiza]

What this code does

  • Each need gets the collection that makes its main operation cheap: HashMap for lookup by train number, TreeMap for "next train after 12:00".
  • HashSet.add returns false for a repeated PNR, and ArrayDeque serves the waiting list in arrival order. Times are stored as numbers like 1640 for 16:40.

Hash-based collections are the fastest for "is it there?" and "what is the value for this key?". Tree-based ones are slower but keep keys sorted and can answer "what is the next key after X?". Linked versions are hash-based plus a remembered insertion order. The O(1) of a hash collection is an average. It needs a good hashCode. If every key returns the same hash code, all keys share one bucket and each lookup becomes a slow search. Java 8 and later turn a very crowded bucket into a small tree, which limits the damage, but a good hashCode is still your job.

  • HashSet / HashMap: add, contains, get, put, remove O(1) on average; no order.
  • LinkedHashSet / LinkedHashMap: the same O(1), plus insertion order; a little more memory.
  • TreeSet / TreeMap: O(log n) for all of them; sorted order, first, ceiling, floor, headMap.
  • Looping over any of them is O(n).

Measuring honestly

System.nanoTime() returns a time in nanoseconds (billionths of a second) that is only useful for measuring gaps: read it before and after, then subtract. A single timing can easily mislead you.

Java
List<Integer> list = new ArrayList<>();for (int i = 0; i < 1_000_000; i++) {    list.add(i);}long best = Long.MAX_VALUE;for (int run = 1; run <= 5; run++) {      // repeat, keep the best    long start = System.nanoTime();    list.contains(-1);                    // only the work is timed    long gap = System.nanoTime() - start;    best = Math.min(best, gap);}System.out.println("Best of 5: " + best / 1_000 + " microseconds");

The JVM gets faster while a program runs: its JIT compiler (just-in-time compiler) turns busy code into fast machine code after a warm-up. Other programs on your computer also steal time.

So repeat each measurement and keep the best time, use data big enough to take at least a few milliseconds, and do not print inside the timed part. Even then, trust the shape ("100 times slower"), not the exact numbers, which change on every computer and every run. Real projects use a benchmark tool such as JMH for this.

Hidden O(n²) traps

A list of 40,000 numbers is made unique twice: with contains on a list and with a HashSet. The program times both.

Example 5 · Common mistake: contains inside a loop

DuplicateCheckDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Random;import java.util.Set;
public class DuplicateCheckDemo {    public static void main(String[] args) {        Random random = new Random(42);        List<Integer> phoneEndings = new ArrayList<>();        for (int i = 0; i < 40_000; i++) {            phoneEndings.add(random.nextInt(100_000));        }
        long start = System.nanoTime();        List<Integer> uniqueList = new ArrayList<>();        for (int x : phoneEndings) {            if (!uniqueList.contains(x)) {                uniqueList.add(x);            }        }        long listMs = (System.nanoTime() - start) / 1_000_000;
        start = System.nanoTime();        Set<Integer> uniqueSet = new HashSet<>();        for (int x : phoneEndings) {            uniqueSet.add(x);        }        long setMs = (System.nanoTime() - start) / 1_000_000;
        System.out.println("Unique values: " + uniqueList.size() + " and " + uniqueSet.size());        System.out.println("List.contains loop: " + listMs + " ms");        System.out.println("HashSet.add loop:   " + setMs + " ms");    }}
Sample output
Unique values: 32874 and 32874
List.contains loop: 402 ms
HashSet.add loop:   5 ms

What this code does

  • Both ways find the same unique values. The list way calls contains, which is O(n), inside a loop of 40,000, so it does hundreds of millions of equals calls.
  • The HashSet way is O(1) per item, about a hundred times faster here. The gap keeps growing as the data grows.

Most slow programs are not slow because of one call; they are slow because an O(n) call sits inside a loop that runs n times. That makes O(n²). The common cases are easy to spot once you know them:

  • if (!list.contains(x)) list.add(x); in a loop → use a HashSet, or a LinkedHashSet to keep order.
  • list.get(i) in an index loop over a LinkedList → use a for-each loop, or an ArrayList.
  • list.remove(0) in a loop over an ArrayList → use an ArrayDeque and poll().
  • Sorting the whole list again after every insert → keep a TreeMap, TreeSet or PriorityQueue instead.

Find the bug

Find the slow line

Select the line that is wrong.

Collect each order id once. Thousands of ids arrive, and this is too slow.

Round 1 of 2

Next step

Check your understanding

12 quick questions