Skip to content

Commit 59c0e15

Browse files
committed
Auto merge of #428 - fornwall:speed-up-clear-on-empty-map, r=Amanieu
Special case `clear()` on empty tables Special case `clear()` to avoid `O(capacity)` runtime even on an empty set. There are workloads which currently needs `if !map.is_empty() { map.clear(); }` for optimal performance, which looks odd (and that it's necessary may be surprising). Special casing empty table aligns with what [java.util.HashMap](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/HashMap.java#L867) is doing. After discussion with `@forny.`
2 parents f2f2882 + 50f2ece commit 59c0e15

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

src/raw/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,10 @@ impl<T, A: Allocator + Clone> RawTable<T, A> {
10271027
/// Removes all elements from the table without freeing the backing memory.
10281028
#[cfg_attr(feature = "inline-more", inline)]
10291029
pub fn clear(&mut self) {
1030+
if self.is_empty() {
1031+
// Special case empty table to avoid surprising O(capacity) time.
1032+
return;
1033+
}
10301034
// Ensure that the table is reset even if one of the drops panic
10311035
let mut self_ = guard(self, |self_| self_.clear_no_drop());
10321036
unsafe {

0 commit comments

Comments
 (0)