https://github.com/andylokandy/smallbox
Small Box optimization: store small item on stack and fallback to heap for large item.
https://github.com/andylokandy/smallbox
alloc box dst rust-lang stack
Last synced: 4 months ago
JSON representation
Small Box optimization: store small item on stack and fallback to heap for large item.
- Host: GitHub
- URL: https://github.com/andylokandy/smallbox
- Owner: andylokandy
- License: mit
- Created: 2017-05-28T09:41:44.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2025-07-02T09:22:04.000Z (8 months ago)
- Last Synced: 2025-09-15T07:37:02.589Z (5 months ago)
- Topics: alloc, box, dst, rust-lang, stack
- Language: Rust
- Homepage:
- Size: 904 KB
- Stars: 90
- Watchers: 1
- Forks: 17
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# SmallBox
[](https://github.com/andylokandy/smallbox/actions/workflows/ci.yml)
[](https://crates.io/crates/smallbox)
[](https://docs.rs/smallbox)
[](https://www.whatrustisit.com)
[](https://github.com/andylokandy/smallbox#license)
A space-efficient alternative to `Box` 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.
## Quick Start
Add SmallBox to your `Cargo.toml`:
```toml
[dependencies]
smallbox = "0.8"
```
### Basic Usage
```rust
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());
```
# Benchmark
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
```
## License
Licensed under either of:
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.