From 809385811d8d82d143e6bc9b3dcf183a7e05f79e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingo=20D=C3=BCppe?= Date: Wed, 18 Nov 2026 08:59:09 +0100 Subject: [PATCH] Add workshop exercise ContainsBenchmark --- README.md | 6 +++ .../exercise/ContainsBenchmark.java | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/main/java/io/crowdcode/java/benchmarks/exercise/ContainsBenchmark.java diff --git a/README.md b/README.md index 601612a..e5e08bf 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,12 @@ mvn archetype:generate -Dversion=1.0-SNAPSHOT ``` +### Workshop Exercise + +`io.crowdcode.java.benchmarks.exercise.ContainsBenchmark` is an unfinished benchmark with `TODO` markers. +It does not show up in `java -jar target/benchmarks.jar -l` until the first benchmark method is added. +The task description and the solution are part of the CROWDCODE workshop material. + ## Benchmark Results REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on diff --git a/src/main/java/io/crowdcode/java/benchmarks/exercise/ContainsBenchmark.java b/src/main/java/io/crowdcode/java/benchmarks/exercise/ContainsBenchmark.java new file mode 100644 index 0000000..2d9915d --- /dev/null +++ b/src/main/java/io/crowdcode/java/benchmarks/exercise/ContainsBenchmark.java @@ -0,0 +1,38 @@ +package io.crowdcode.java.benchmarks.exercise; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Exercise: from which collection size on does a {@link HashSet} pay off + * compared to an {@link ArrayList} when calling {@code contains()}? + */ +// TODO 1: turn this class into a JMH state object with one instance per benchmark thread +public class ContainsBenchmark { + + // TODO 2: let JMH run the benchmark for the sizes 1, 10, 1000 and 100000 + int size; + + List list; + Set set; + Integer searched; + + // TODO 3: let JMH call this method once before each trial + public void fillCollections() { + list = new ArrayList<>(size); + set = new HashSet<>(size); + for (int i = 0; i < size; i++) { + list.add(i); + set.add(i); + } + // worst case for the list: the searched element is the last one + searched = size - 1; + } + + // TODO 4: add a benchmark method "listContains" that searches the element in the list + + // TODO 5: add a benchmark method "setContains" that searches the element in the set + +}