Skip to content

Commit

Permalink
Faster LinkedHashSet head() (#2728)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
j-baker authored and pivovarit committed Aug 19, 2024
1 parent ba9ed24 commit a75090d
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions vavr/src/main/java/io/vavr/collection/LinkedHashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> headOption() {
return iterator().headOption();
return map.headOption().map(Tuple2::_1);
}

@Override
Expand Down

0 comments on commit a75090d

Please # to comment.