Skip to content

Commit 0f547a9

Browse files
authored
Rollup merge of #162931 - ywxt:btree_map_drop, r=Amanieu
directly deallocates the nodes instead of traversing every element when BTreemap dropping When BTreeMap is dropping, it currently turns the tree into an iterator and traverses the kvs, updating the LazyLeafRange after each element is dropped. This is unnecessary during destruction. We can instead traverse the tree node by node and drop the kvs directly from each node. Results on aarch64: - btree::map benchmark | baseline | without drop | change | with drop | change | pp diff (with − without) -- | -- | -- | -- | -- | -- | -- clone_fat_val_100 | 10849.14 | 7433.38 | -31.5% | 7573.66 | -30.2% | +1.3pp clone_fat_val_100_and_clear | 11021.05 | 7606.91 | -31.0% | 7769.49 | -29.5% | +1.5pp clone_fat_val_100_and_drain_all | 57652.20 | 55026.07 | -4.6% | 55495.20 | -3.7% | +0.8pp clone_fat_val_100_and_drain_half | 27258.25 | 23993.80 | -12.0% | 24005.43 | -11.9% | +0.0pp clone_fat_val_100_and_into_iter | 15149.81 | 12289.52 | -18.9% | 12401.29 | -18.1% | +0.7pp clone_fat_val_100_and_pop_all | 56717.62 | 54045.12 | -4.7% | 54643.59 | -3.7% | +1.1pp clone_fat_val_100_and_remove_all | 64333.00 | 61907.57 | -3.8% | 62039.79 | -3.6% | +0.2pp clone_fat_val_100_and_remove_half | 28440.43 | 25290.79 | -11.1% | 25634.00 | -9.9% | +1.2pp clone_slim_100 | 1978.26 | 687.38 | -65.3% | 798.38 | -59.6% | +5.6pp clone_slim_100_and_clear | 1908.35 | 687.58 | -64.0% | 796.25 | -58.3% | +5.7pp clone_slim_100_and_drain_all | 3983.43 | 4244.24 | +6.5% | 4123.55 | +3.5% | -3.0pp clone_slim_100_and_drain_half | 4241.43 | 3551.33 | -16.3% | 3624.14 | -14.6% | +1.7pp clone_slim_100_and_into_iter | 1805.39 | 1753.37 | -2.9% | 1840.42 | +1.9% | +4.8pp clone_slim_100_and_pop_all | 3243.54 | 3247.17 | +0.1% | 3321.00 | +2.4% | +2.3pp clone_slim_100_and_remove_all | 5203.97 | 5176.58 | -0.5% | 5282.19 | +1.5% | +2.0pp clone_slim_100_and_remove_half | 2399.04 | 1818.85 | -24.2% | 1929.16 | -19.6% | +4.6pp clone_slim_10k | 205051.50 | 74942.50 | -63.5% | 83515.00 | -59.3% | +4.2pp clone_slim_10k_and_clear | 197575.50 | 74994.75 | -62.0% | 82934.71 | -58.0% | +4.0pp clone_slim_10k_and_drain_all | 425268.00 | 424679.50 | -0.1% | 432531.75 | +1.7% | +1.8pp clone_slim_10k_and_drain_half | 408679.00 | 358468.67 | -12.3% | 366904.50 | -10.2% | +2.1pp clone_slim_10k_and_into_iter | 184573.50 | 180805.00 | -2.0% | 188245.25 | +2.0% | +4.0pp clone_slim_10k_and_pop_all | 369476.00 | 370334.50 | +0.2% | 378684.50 | +2.5% | +2.3pp clone_slim_10k_and_remove_all | 582219.44 | 581719.69 | -0.1% | 590480.50 | +1.4% | +1.5pp clone_slim_10k_and_remove_half | 424686.50 | 373048.00 | -12.2% | 382718.00 | -9.9% | +2.3pp from_iter_rand_100 | 1832.99 | 1086.70 | -40.7% | 1194.53 | -34.8% | +5.9pp from_iter_rand_10_000 | 304447.00 | 231011.33 | -24.1% | 234360.00 | -23.0% | +1.1pp from_iter_seq_100 | 2045.17 | 750.12 | -63.3% | 896.15 | -56.2% | +7.1pp from_iter_seq_10_000 | 211268.33 | 80514.29 | -61.9% | 85877.83 | -59.4% | +2.5pp - btree::set benchmark | baseline | without drop | change | with drop | change | pp diff (with − without) -- | -- | -- | -- | -- | -- | -- clone_100 | 1913.17 | 605.95 | -68.3% | 745.54 | -61.0% | +7.3pp clone_100_and_clear | 1813.35 | 608.09 | -66.5% | 743.81 | -59.0% | +7.5pp clone_100_and_drain_all | 3960.52 | 3965.28 | +0.1% | 4088.26 | +3.2% | +3.1pp clone_100_and_drain_half | 4045.63 | 3408.90 | -15.7% | 3559.55 | -12.0% | +3.7pp clone_100_and_into_iter | 1676.32 | 1600.11 | -4.5% | 1721.67 | +2.7% | +7.3pp clone_100_and_pop_all | 2582.26 | 2562.19 | -0.8% | 2686.39 | +4.0% | +4.8pp clone_100_and_remove_all | 4574.45 | 4520.84 | -1.2% | 4671.70 | +2.1% | +3.3pp clone_100_and_remove_half | 2107.02 | 1533.22 | -27.2% | 1673.91 | -20.6% | +6.7pp clone_10k | 192719.50 | 65933.38 | -65.8% | 75038.88 | -61.1% | +4.7pp clone_10k_and_clear | 184669.60 | 66101.87 | -64.2% | 75375.25 | -59.2% | +5.0pp clone_10k_and_drain_all | 418832.00 | 417920.00 | -0.2% | 424436.00 | +1.3% | +1.6pp clone_10k_and_drain_half | 400446.00 | 348149.50 | -13.1% | 351997.00 | -12.1% | +1.0pp clone_10k_and_into_iter | 170359.60 | 163481.80 | -4.0% | 165757.25 | -2.7% | +1.3pp clone_10k_and_pop_all | 306021.67 | 307441.67 | +0.5% | 307585.00 | +0.5% | +0.0pp clone_10k_and_remove_all | 510750.88 | 511582.56 | +0.2% | 512938.25 | +0.4% | +0.3pp clone_10k_and_remove_half | 385672.00 | 337072.33 | -12.6% | 341705.50 | -11.4% | +1.2pp r? @Amanieu
2 parents b35d551 + 926a9d0 commit 0f547a9

4 files changed

Lines changed: 220 additions & 9 deletions

File tree

‎library/alloc/src/collections/btree/map.rs‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -205,16 +205,13 @@ pub struct BTreeMap<
205205
#[stable(feature = "btree_drop", since = "1.7.0")]
206206
unsafe impl<#[may_dangle] K, #[may_dangle] V, A: AllocatorClone> Drop for BTreeMap<K, V, A> {
207207
fn drop(&mut self) {
208-
// Skip `into_iter` for an empty map: `dying_next` is too costly to inline, so the
209-
// empty drop isn't optimised away (see #161375).
210-
if self.root.is_some() {
211-
// SAFETY: `self` is not used after this and none of its fields are dropped again:
212-
// `alloc` is `ManuallyDrop` and `root` has no drop glue.
213-
drop(unsafe { ptr::read(self) }.into_iter())
208+
if let Some(root) = self.root.take() {
209+
// SAFETY: The tree won't be used after this point.
210+
// The allocator has not been moved out and will be moved into `drop_tree`.
211+
unsafe { root.into_dying().drop_tree(ManuallyDrop::take(&mut self.alloc)) };
214212
} else {
215-
// SAFETY: With no root there are no nodes to free, so only the allocator needs
216-
// dropping. `self` is not used after this, and `alloc` is dropped only here.
217-
unsafe { ManuallyDrop::drop(&mut self.alloc) }
213+
// SAFETY: The allocator has not been moved out and won't be used after this point.
214+
unsafe { ManuallyDrop::drop(&mut self.alloc) };
218215
}
219216
}
220217
}

‎library/alloc/src/collections/btree/map/tests.rs‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2542,6 +2542,114 @@ fn test_into_iter_drop_leak_height_1() {
25422542
}
25432543
}
25442544

2545+
#[test]
2546+
fn test_drop_map_elements_multi_level() {
2547+
for size in [1, MIN_INSERTS_HEIGHT_1, MIN_INSERTS_HEIGHT_2] {
2548+
let keys = Vec::from_iter((0..size).map(CrashTestDummy::new));
2549+
let vals = Vec::from_iter((0..size).map(CrashTestDummy::new));
2550+
let map = {
2551+
let mut map = BTreeMap::new();
2552+
2553+
(0..size).map(|i| (keys[i].spawn(Panic::Never), vals[i].spawn(Panic::Never))).for_each(
2554+
|(k, v)| {
2555+
map.insert(k, v);
2556+
},
2557+
);
2558+
map
2559+
};
2560+
2561+
drop(map);
2562+
2563+
for i in 0..size {
2564+
assert_eq!(keys[i].dropped(), 1);
2565+
assert_eq!(vals[i].dropped(), 1);
2566+
}
2567+
}
2568+
}
2569+
2570+
#[test]
2571+
fn test_drop_empty_map_allocator() {
2572+
use core::alloc::{AllocError, Allocator, AllocatorClone, Layout};
2573+
use core::cell::Cell;
2574+
use core::ptr::NonNull;
2575+
2576+
struct CountedAllocator<'a>(&'a Cell<usize>);
2577+
2578+
impl Clone for CountedAllocator<'_> {
2579+
fn clone(&self) -> Self {
2580+
Self(self.0)
2581+
}
2582+
}
2583+
2584+
impl Drop for CountedAllocator<'_> {
2585+
fn drop(&mut self) {
2586+
self.0.set(self.0.get() + 1);
2587+
}
2588+
}
2589+
2590+
unsafe impl Allocator for CountedAllocator<'_> {
2591+
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2592+
Global.allocate(layout)
2593+
}
2594+
2595+
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2596+
unsafe { Global.deallocate(ptr, layout) }
2597+
}
2598+
}
2599+
2600+
unsafe impl AllocatorClone for CountedAllocator<'_> {}
2601+
2602+
let dropped = Cell::new(0);
2603+
let map = BTreeMap::<i32, i32, _>::new_in(CountedAllocator(&dropped));
2604+
assert!(map.root.is_none());
2605+
2606+
drop(map);
2607+
2608+
assert_eq!(dropped.get(), 1);
2609+
}
2610+
2611+
#[test]
2612+
#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
2613+
fn test_drop_map_elements_multi_level_panic() {
2614+
for size in [1, MIN_INSERTS_HEIGHT_1, MIN_INSERTS_HEIGHT_2] {
2615+
for panic_point in [0, size / 2, size - 1] {
2616+
for panic_in_key in [true, false] {
2617+
let keys = Vec::from_iter((0..size).map(CrashTestDummy::new));
2618+
let vals = Vec::from_iter((0..size).map(CrashTestDummy::new));
2619+
let map = {
2620+
let mut map = BTreeMap::new();
2621+
2622+
(0..size)
2623+
.map(|i| {
2624+
let key_panic = if panic_in_key && i == panic_point {
2625+
Panic::InDrop
2626+
} else {
2627+
Panic::Never
2628+
};
2629+
let val_panic = if !panic_in_key && i == panic_point {
2630+
Panic::InDrop
2631+
} else {
2632+
Panic::Never
2633+
};
2634+
(keys[i].spawn(key_panic), vals[i].spawn(val_panic))
2635+
})
2636+
.for_each(|(k, v)| {
2637+
map.insert(k, v);
2638+
});
2639+
map
2640+
};
2641+
2642+
catch_unwind(move || drop(map)).unwrap_err();
2643+
2644+
for i in 0..size {
2645+
assert_eq!(keys[i].dropped(), 1);
2646+
assert_eq!(vals[i].dropped(), 1);
2647+
}
2648+
}
2649+
}
2650+
}
2651+
}
2652+
25452653
#[test]
25462654
fn test_into_keys() {
25472655
let map = BTreeMap::from([(1, 'a'), (2, 'b'), (3, 'c')]);

‎library/alloc/src/collections/btree/navigate.rs‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,3 +852,70 @@ impl<BorrowType: marker::BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Lea
852852
}
853853
}
854854
}
855+
856+
impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
857+
/// # Safety
858+
/// - `self` must be the root.
859+
/// - The tree shouldn't be accessed anymore.
860+
pub(super) unsafe fn drop_tree<A: AllocatorClone>(self, alloc: A) {
861+
struct DropGuard<K, V, A: AllocatorClone> {
862+
node: Option<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>>,
863+
alloc: A,
864+
}
865+
866+
impl<K, V, A: AllocatorClone> Drop for DropGuard<K, V, A> {
867+
fn drop(&mut self) {
868+
if let Some(cur) = self.node.take() {
869+
let mut next =
870+
// SAFETY: When unwinding reached this guard, all kvs in cur
871+
// have already been dropped in `drop_kvs`, while the node itself has not
872+
// yet been deallocated.
873+
unsafe { deallocate_and_next_postorder_node(cur, self.alloc.clone()) };
874+
875+
while let Some(mut node) = next {
876+
// SAFETY: Every node only calls the function once
877+
unsafe { node.drop_kvs() };
878+
next =
879+
// SAFETY: `drop_kvs()` above only dropped kvs and the node is still accessible,
880+
// and also each node is deallocated exactly once.
881+
unsafe { deallocate_and_next_postorder_node(node, self.alloc.clone()) }
882+
}
883+
}
884+
}
885+
}
886+
/// Deallocates `node` and returns the next node in postorder traversal
887+
///
888+
/// # Safety
889+
///
890+
/// The node must be initialized, all kvs in node must have already
891+
/// been dropped or moved out and its children must have already been deallocated.
892+
/// Also the node can't be touched anymore.
893+
unsafe fn deallocate_and_next_postorder_node<K, V, A: AllocatorClone>(
894+
node: NodeRef<marker::Dying, K, V, marker::LeafOrInternal>,
895+
alloc: A,
896+
) -> Option<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>> {
897+
// SAFETY: guaranteed by the caller
898+
let parent = unsafe { node.deallocate_and_ascend(alloc) }?;
899+
900+
Some(match parent.right_kv() {
901+
Ok(kv) => kv.right_edge().descend().first_leaf_edge().into_node().forget_type(),
902+
Err(last_edge) => last_edge.into_node().forget_type(),
903+
})
904+
}
905+
906+
let node = self.first_leaf_edge().into_node().forget_type();
907+
let mut guard = DropGuard { node: Some(node), alloc };
908+
loop {
909+
// SAFETY: all kvs of each node are dropped once
910+
unsafe { guard.node.as_mut().unwrap().drop_kvs() };
911+
// SAFETY: Nodes are deallocated in postorder, and each node is deallocated exactly once.
912+
if let Some(next) = unsafe {
913+
deallocate_and_next_postorder_node(guard.node.take().unwrap(), guard.alloc.clone())
914+
} {
915+
guard.node = Some(next);
916+
} else {
917+
return;
918+
}
919+
}
920+
}
921+
}

‎library/alloc/src/collections/btree/node.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,45 @@ impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
429429
}
430430
ret
431431
}
432+
/// Drops all kvs in this node without deallocating the node itself
433+
///
434+
/// # Safety
435+
///
436+
/// - kvs in the node must be initialized and must not be accessed after this call.
437+
/// - No kvs in the node can be accessed through any other path while this function is running.
438+
pub(super) unsafe fn drop_kvs(&mut self) {
439+
struct DropGuard<'a, K, V> {
440+
node: &'a NodeRef<marker::Dying, K, V, marker::LeafOrInternal>,
441+
idx: usize,
442+
}
443+
impl<'a, K, V> Drop for DropGuard<'a, K, V> {
444+
fn drop(&mut self) {
445+
let len = self.node.len();
446+
for i in self.idx..len {
447+
// SAFETY: i < len and the kv has been initialized and
448+
// it won't use the i-th kv more than once.
449+
unsafe {
450+
let kv = Handle::new_kv(ptr::read(self.node), i);
451+
kv.drop_key_val();
452+
}
453+
}
454+
}
455+
}
456+
let len = self.len();
457+
for idx in 0..len {
458+
// If `kv.drop_key_val()` panics, the guard would drop
459+
// the rest and skip the panicked kv.
460+
let guard = DropGuard { node: self, idx: idx + 1 };
461+
// SAFETY: idx < len and the kv has been initialized and
462+
// it won't touch the idx-th more than once
463+
unsafe {
464+
let kv = Handle::new_kv(ptr::read(self), idx);
465+
kv.drop_key_val();
466+
}
467+
468+
core::mem::forget(guard);
469+
}
470+
}
432471
}
433472

434473
impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {

0 commit comments

Comments
 (0)