How to Use MaybeUninit for Performance-Critical Code

Use MaybeUninit to skip zero-initialization overhead by manually writing values into uninitialized memory and then assuming initialization.

Use MaybeUninit<T> to allocate uninitialized memory, write values into it using ptr::write, and then safely convert it to an initialized T with assume_init() to avoid zero-initialization costs.

use std::mem::MaybeUninit;

fn fast_alloc() -> i32 {
    let mut uninit = MaybeUninit::<i32>::uninit();
    unsafe {
        std::ptr::write(uninit.as_mut_ptr(), 42);
        uninit.assume_init()
    }
}

This pattern is critical in performance-sensitive code, such as arena allocators like TypedArena, where avoiding the overhead of zeroing memory for every allocation significantly improves speed.