The Cost of Drop on Deep Ownership Chains
The Cost of Drop on Deep Ownership Chains
Thesis
Drop is not free. A long chain of Box nodes runs destructors one by one; mem::forget skips them and returns in nanoseconds — which is also how you leak. This chapter times dropping chains of 1 k / 10 k / 100 k nodes versus forgetting the large chain.
Mental model
drop(head) → Drop::drop → drop(child) → … (recursive / iterative cleanup)
mem::forget(head) → no destructors; memory leaked unless into a global allocator you never reclaim
Worked examples
Verified with rustc 1.99.1, cargo run --release.
// chain of Box<Node>; time drop vs forgetOutput:
drop chain of 1000 nodes: 21.888µs
drop chain of 10000 nodes: 267.357µs
drop chain of 100000 nodes: 4.211461ms
forget chain of 100000 nodes: 487ns
Drop scales with chain length (~4 ms for 100 k nodes here). forget on the same shape was ~0.5 µs — and leaked the graph.
Trap
Using forget to “speed up shutdown”. You trade CPU for leaks and skipped safety hooks (File flush, lock poisoning cleanup, etc.).
Boring rule
Let Drop run. If shutdown profiles show destructor cost, batch into arenas or reuse pools — do not forget application state.
Try this
- Replace the linked list with a
Vec<Node>and compare drop time. - Implement
Dropfor a type that prints, and watch ordering. - Read
std::mem::ManuallyDrop.