Skip to content

Compiler optimizationΒ #17

Open
Open
@tkaitchuck

Description

@tkaitchuck

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions