The release build likely optimizes out the whole thing because it doesn't do anything externally observable.
This is.
By the way, your test function has UB. If your array elements are not all initialized, then you must not create a slice with the initialized type. References must always point to valid (initialized) values.
Thank you for answers. I have updated function to:
fn test_function ()
{
let mut buffer_uninit: [MaybeUninit<u8>; MAX_LEN] = MaybeUninit::uninit_array();
let mut buffer: &mut [u8] = unsafe {
let ptr = buffer_uninit.as_mut_ptr() as *mut u8;
std::slice::from_raw_parts_mut(ptr, buffer_uninit.len())
};
unsafe {
for i in 0..buffer.len()
{
buffer [i] = rand() as u8;
}
}
}
This is quick "load", to make function do something observable, additionally to init the array.
But the question is still, why in DEBUG mode it takes seconds (!!!!!!) (and maybe minutes) and in RELEASE mode it takes nanoseconds ??? When the buffer length is small enough (MAX_LEN) it works quickly, but with large values it takes for seconds to only get uninit array ???
Your function still doesn't do anything observable, since it doesn't return anything or access any memory outside the function (through a reference passed in, for example). It also still has undefined behaviour because it still creates a &mut [u8] pointing to uninitialised memory.
The correct way to work with uninitialised memory is to intialise it using write()before converting it to some initialised type.
Thanks. The test function actually now fills in random data into buffer. And it is observable.
The general problem:
I have a large array in stack. I need, it to have it uninitialized on the first stage. Because, I don't see any sense to init it, and waste CPU time. For example, on the next stage of the program, it will be filled with data of user input. So. what is the sense to init it, when data will be later overwritten with new values ? In C and С++, it could be done easily. And in rust, having large stack leads to slow program for minutes ...
emmm... I'm not an expert in compiler
I think we can't optimize it(in dev profile)? In llvm-ir generated by rustc (with -C opt-level=0, same as cargo's dev profile):