Skip to content

Commit f41a6fa

Browse files
authored
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.
1 parent f37e9ef commit f41a6fa

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

src/main/java/io/vavr/collection/LinkedHashSet.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -631,12 +631,12 @@ public T head() {
631631
if (map.isEmpty()) {
632632
throw new NoSuchElementException("head of empty set");
633633
}
634-
return iterator().next();
634+
return map.head()._1();
635635
}
636636

637637
@Override
638638
public Option<T> headOption() {
639-
return iterator().headOption();
639+
return map.headOption().map(Tuple2::_1);
640640
}
641641

642642
@Override

0 commit comments

Comments
 (0)