Skip to content

Commit 1ae2a81

Browse files
committed
perf: use alloc zeroed to implement calloc
Allocating zeroed memory is faster than zeroing memory manually
1 parent b633b29 commit 1ae2a81

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

crates/hyperion/src/alloc.rs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::{
2-
alloc::{Layout, alloc, dealloc, realloc},
2+
alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc},
33
ptr::null_mut,
44
sync::OnceLock,
55
};
@@ -21,7 +21,7 @@ fn get_size_map() -> &'static papaya::HashMap<usize, usize> {
2121
unsafe { ALLOC_SIZES.get().unwrap_unchecked() }
2222
}
2323

24-
unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::c_void {
24+
unsafe fn aligned_alloc(size: ecs_size_t, custom_alloc: fn(Layout) -> *mut u8) -> *mut core::ffi::c_void {
2525
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
2626
let size = size as usize;
2727

@@ -30,7 +30,7 @@ unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::
3030
return null_mut();
3131
};
3232

33-
let ptr = unsafe { alloc(layout) };
33+
let ptr = unsafe { custom_alloc(layout) };
3434

3535
if ptr.is_null() {
3636
return null_mut();
@@ -42,17 +42,12 @@ unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::
4242
ptr.cast::<core::ffi::c_void>()
4343
}
4444

45-
unsafe extern "C-unwind" fn aligned_calloc(size: ecs_size_t) -> *mut core::ffi::c_void {
46-
let ptr = unsafe { aligned_malloc(size) };
47-
if !ptr.is_null() {
48-
// Zero the entire allocation
49-
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
50-
unsafe {
51-
std::ptr::write_bytes(ptr, 0, size as usize);
52-
};
53-
}
45+
unsafe extern "C-unwind" fn aligned_malloc(size: ecs_size_t) -> *mut core::ffi::c_void {
46+
aligned_alloc(size, alloc)
47+
}
5448

55-
ptr
49+
unsafe extern "C-unwind" fn aligned_calloc(size: ecs_size_t) -> *mut core::ffi::c_void {
50+
aligned_alloc(size, alloc_zeroed)
5651
}
5752

5853
unsafe extern "C-unwind" fn aligned_realloc(

0 commit comments

Comments
 (0)