Created
September 4, 2023 03:51
-
-
Save shqld/2b81fb4dd87ebf9c6c11f42451599913 to your computer and use it in GitHub Desktop.
Rust generic function monomorphization optimization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code, unused_variables, clippy::from_over_into)] | |
struct Inner { | |
raw: *mut [u8; 0], | |
} | |
struct Object { | |
inner: Inner, | |
} | |
impl AsRef<Inner> for Object { | |
#[inline(never)] | |
fn as_ref(&self) -> &Inner { | |
&self.inner | |
} | |
} | |
struct SameObject { | |
inner: Inner, | |
} | |
impl AsRef<Inner> for SameObject { | |
#[inline(never)] | |
fn as_ref(&self) -> &Inner { | |
&self.inner | |
} | |
} | |
struct SameObjectWithPadding { | |
inner: Inner, | |
_padding: u8, | |
} | |
impl AsRef<Inner> for SameObjectWithPadding { | |
#[inline(never)] | |
fn as_ref(&self) -> &Inner { | |
&self.inner | |
} | |
} | |
struct SameObjectWithAnotherImpl { | |
c: Inner, | |
} | |
impl AsRef<Inner> for SameObjectWithAnotherImpl { | |
#[inline(never)] | |
fn as_ref(&self) -> &Inner { | |
println!("c"); | |
&self.c | |
} | |
} | |
#[inline(never)] | |
fn take_any_struct(any_struct: impl AsRef<Inner>) { | |
let inner = any_struct.as_ref(); | |
std::hint::black_box(inner); | |
} | |
fn main() { | |
let object = Object { | |
inner: Inner { | |
raw: std::ptr::null_mut(), | |
}, | |
}; | |
let same_object = SameObject { | |
inner: Inner { | |
raw: std::ptr::null_mut(), | |
}, | |
}; | |
let same_object_with_padding = SameObjectWithPadding { | |
inner: Inner { | |
raw: std::ptr::null_mut(), | |
}, | |
_padding: 42, | |
}; | |
let same_object_with_another_impl = SameObjectWithAnotherImpl { | |
c: Inner { | |
raw: std::ptr::null_mut(), | |
}, | |
}; | |
take_any_struct(&object); | |
take_any_struct(object); | |
take_any_struct(&same_object); | |
take_any_struct(same_object); | |
take_any_struct(&same_object_with_padding); | |
take_any_struct(same_object_with_padding); | |
take_any_struct(&same_object_with_another_impl); | |
take_any_struct(same_object_with_another_impl); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unified
take_any_struct(&object)
&take_any_struct(&same_object)
take_any_struct(object)
&take_any_struct(same_object)