Command Palette

Search for a command to run...

Back to the lesson: Topic 14.6 — Everyday Performance Pitfalls
Core Java · Example 2 of 3 Java 16+

The hidden O(n²): List.contains in a loop

Counting work instead of timing it gives a deterministic, honest comparison. The set calls equals only when hash codes match, which here means only for real duplicates. LinkedHashSet keeps first-seen order, so the result is the same list.

Most slow Java code is slow for a handful of ordinary reasons: the wrong algorithm or collection, needless allocation and boxing, string building in loops, exceptions and logging in hot paths, lock contention, and I/O done one byte or one query at a time. Measure first, fix the biggest cost, and measure again.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite a method that joins 1 to 10 with commas using += into one using StringJoiner, and print the result.

02

Given an array of 10 ints with duplicates, count distinct values using a HashSet instead of nested loops, and print the count.

03

Write a static final Pattern that matches product codes like ABC-1234, test it on three inputs, and print the results.

Explain it without notes

01

How do you approach a "the service is slow" report?

02

Why is s += x in a loop slow, and why is a + b + c not?

03

What are the costs of autoboxing, and how do you avoid them?

04

What is the N+1 query problem and how do you fix it?

The hidden O(n²): List.contains in a loop Java 16+
Sign in to run this example in your browser.

Expected output

unique (list): 2000, equals calls: 4000000
unique (set):  2000, equals calls: 2000
same order:    true