arrayref icon indicating copy to clipboard operation
arrayref copied to clipboard

Compiler optimization

Open tkaitchuck opened this issue 5 years ago • 2 comments

For whatever reason when I use array_ref!() and then look at the generated assembly, I can see the compiler for whatever reason is not able to elude the bounds checking when the array is split inside of the macro. This happens even at -O 3, and it is directly surrounded by an if check on the length of the slice. I was able to work around it, by moving the slice outside of the macro. Creating a new macro where the caller has to pre-slice things so the sliced passed in is exactly the side of the desired array.

macro_rules! as_array {
    ($input:expr, $len:expr) => {{
        {
            #[inline]
            fn as_array<T>(slice: &[T]) -> &[T; $len] {
                assert_eq!(slice.len(), $len);
                unsafe {
                    &*(slice.as_ptr() as *const [_; $len])
                }
            }
            as_array($input)
        }
    }}
}

While this is a little more awkward to call, it is a lot easier to explain and because the compiler is able to elude the bounds checks performs better. It may be worth incorporating this method.

tkaitchuck avatar Mar 01 '19 07:03 tkaitchuck

Are you thinking that using as_array! internally in array_ref! could improve compiler optimizations?

droundy avatar Mar 01 '19 22:03 droundy

Yes. When I use the array_ref and look at the assembly generated it always seems to have a branch to panic in the event that the length is out of bounds, even when it's enclosed in an if statement explicitly testing the length. I'm not sure why. Something about the way the code gets structured.

tkaitchuck avatar Apr 05 '19 17:04 tkaitchuck