Skip to content

Instantly share code, notes, and snippets.

@mrhampson
Created August 9, 2018 20:03
Show Gist options
  • Select an option

  • Save mrhampson/eb15c9a2c1d29ba508d1097648d338d1 to your computer and use it in GitHub Desktop.

Select an option

Save mrhampson/eb15c9a2c1d29ba508d1097648d338d1 to your computer and use it in GitHub Desktop.
Test which contains is faster ArrayList vs HashSet
import com.liveaction.commons.monitor.Timer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
class Scratch {
public static void main(String[] args) {
// List seems to start losing around 50
int listCount = 50;
int attemptCount = 1_000_000;
List<UUID> list = new ArrayList<>(listCount);
Set<UUID> set = new HashSet<>(listCount);
UUID idToFind = null;
for (int i = 0; i < listCount; i++) {
UUID id = UUID.randomUUID();
list.add(id);
set.add(id);
if (i == listCount/2) {
idToFind = id;
}
}
Timer setTimer = new Timer();
Timer listTimer = new Timer();
boolean found = false;
for (int i = 0; i < attemptCount; i++) {
setTimer.start();
if (set.contains(idToFind)) {
found = true;
}
setTimer.stop();
}
System.out.println("Set contains (avg) ns: " + setTimer.getAverageTimeNanos());
found = false;
for (int i = 0; i < attemptCount; i++) {
listTimer.start();
if (list.contains(idToFind)) {
found = true;
}
listTimer.stop();
}
System.out.println("List contains (avg) ns: " + listTimer.getAverageTimeNanos());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment