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 committed Jan 3, 2023
1 parent f37e9ef commit f41a6fa
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/main/java/io/vavr/collection/LinkedHashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> headOption() {
return iterator().headOption();
return map.headOption().map(Tuple2::_1);
}

@Override
Expand Down

0 comments on commit f41a6fa

Please sign in to comment.