From 4bc274d1a6deda89c26be748736a588004690cbe Mon Sep 17 00:00:00 2001 From: James Baker Date: Tue, 29 Nov 2022 12:27:13 +0000 Subject: [PATCH] Faster LinkedHashSet head() 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. --- src/main/java/io/vavr/collection/LinkedHashSet.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/vavr/collection/LinkedHashSet.java b/src/main/java/io/vavr/collection/LinkedHashSet.java index 92c5d60b2..dba6ebfbb 100644 --- a/src/main/java/io/vavr/collection/LinkedHashSet.java +++ b/src/main/java/io/vavr/collection/LinkedHashSet.java @@ -631,12 +631,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