From a75090d1d49c5b6b2055336d2a990cc01be85712 Mon Sep 17 00:00:00 2001 From: James Baker Date: Tue, 3 Jan 2023 11:05:10 +0000 Subject: [PATCH] Faster LinkedHashSet head() (#2728) While writing up #2727 I noticed that `LinkedHashSet.head()` is implemented `iterator().head()`. This is inefficient because `queue.iterator().next()` makes a call to `.head()`, but also to `.tail()` so as to prepare for the next `head()` call. Given the structure of the underlying `Queue`, the `head()` call is worst case `O(1)` but the tail call is worst case `O(n)`. The present worst case will be achieved if there have never been overwrites or removals from the set, which is probably a fairly common case. --- vavr/src/main/java/io/vavr/collection/LinkedHashSet.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vavr/src/main/java/io/vavr/collection/LinkedHashSet.java b/vavr/src/main/java/io/vavr/collection/LinkedHashSet.java index d6bfc505b..865bc5d98 100644 --- a/vavr/src/main/java/io/vavr/collection/LinkedHashSet.java +++ b/vavr/src/main/java/io/vavr/collection/LinkedHashSet.java @@ -641,12 +641,12 @@ public T head() { if (map.isEmpty()) { throw new NoSuchElementException("head of empty set"); } - return iterator().next(); + return map.head()._1(); } @Override public Option headOption() { - return iterator().headOption(); + return map.headOption().map(Tuple2::_1); } @Override