我有一些代碼,我經常使用unwrap()
模式下,我可以肯定它不會恐慌。其中一些片斷處於性能關鍵功能,所以我想知道是否應該刪除這些unwrap()
以支持未經檢查的適用函數變體。但是,我沒有看到與#[bench]
測試有任何區別,並且這兩個變體的ASM看起來與我很相似(儘管我不是專家)。是否在優化模式下展開()?
看來Rust能夠優化這種情況;我是對的還是應該使用未經檢查的功能而不是unwrap()
?
MCVE:
use self::Foo::*;
use self::Error::*;
#[derive(Debug)]
enum Foo {
Bar(Box<Foo>),
Baz
}
#[derive(Debug)]
enum Error {
NotBar
}
impl Foo {
fn bar_mut_ref(&mut self) -> Result<&mut Foo, Error> {
match *self {
Bar(ref mut foo) => Ok(foo),
_ => Err(NotBar)
}
}
fn bar_mut_ref_unchecked(&mut self) -> &mut Foo {
match *self {
Bar(ref mut foo) => foo,
_ => panic!("bar_mut_ref_unchecked() called on a non-Bar!")
}
}
fn bazify(&mut self) {
match *self {
Bar(_) => { *self = Baz },
_ =>()
}
}
}
fn do_stuff_with_foo(foo: &mut Foo) {
match *foo {
Bar(_) => {
foo.bar_mut_ref().unwrap().bazify(); // is _unchecked() better here?
// underscore was used because foo is assigned to a new value here
},
_ => {}
}
}
fn main() {
let mut foo = Bar(Box::new(Bar(Box::new(Baz))));
do_stuff_with_foo(&mut foo);
println!("{:?}", foo);
}
至於所有的微觀優化問題:如果這不是問題,請使用安全的替代方案。 –
@ildjarn:我在[Rust playground](https://play.rust-lang.org)上做了檢查。我可以看到,您鏈接的ASM是用一組特定的標誌編譯的,以將其大小減小到功能最小值;這非常方便。 – ljedrz
@MatthieuM .:這很有道理,但在這種情況下,兩種變體都是同樣安全的。 – ljedrz