A space-efficient alternative to Box<T> that stores small values on the stack and falls back to heap allocation for larger values. This optimization can significantly reduce memory allocations and improve performance for applications working with many small objects.
Add SmallBox to your Cargo.toml:
[dependencies]
smallbox = "0.8"use smallbox::SmallBox;
use smallbox::space::S4;
// Small values are stored on the stack
let small: SmallBox<[u32; 2], S4> = SmallBox::new([1, 2]);
assert!(!small.is_heap());
// Large values automatically use heap allocation
let large: SmallBox<[u32; 32], S4> = SmallBox::new([0; 32]);
assert!(large.is_heap());
// Use like a regular Box
println!("Small: {:?}, Large: {:?}", *small, large.len());The test platform is Ubuntu 2204 on AMD Ryzen 9 7950X3D 16-Core Processor.
compare fastest โ slowest โ median โ mean โ samples โ iters
โโ box_large_item 13.96 ns โ 14.44 ns โ 14.2 ns โ 14.16 ns โ 100 โ 12800
โโ box_small_item 7.313 ns โ 7.512 ns โ 7.391 ns โ 7.392 ns โ 100 โ 25600
โโ smallbox_large_item_large_space 14.13 ns โ 49.42 ns โ 14.9 ns โ 15.07 ns โ 100 โ 12800
โโ smallbox_large_item_small_space 23.91 ns โ 26.09 ns โ 25 ns โ 24.94 ns โ 100 โ 6400
โโ smallbox_small_item_large_space 0.995 ns โ 1.025 ns โ 1.005 ns โ 1.003 ns โ 100 โ 102400
โฐโ smallbox_small_item_small_space 0.985 ns โ 1.015 ns โ 0.995 ns โ 0.996 ns โ 100 โ 102400
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.