Does function that accepts FnOnce is going to be optimized?


#1
struct Storage {
    items: Vec<Item>,
}

impl Storage {
    fn apply<F: FnMut(&mut Item)>(&mut self, func: F) {
        for item in &mut self.items {
            func(item);
        }
    }
}

fn main() {
    let mut storage = /* Implementation details */;
    storage.apply(|item| {
        item.do_something();
    });
}

Will closure be inlined?


#2

Maybe?

There’s nothing that inherently prevents callable types from being inlined. But answering “will it be inlined” in general is impossible, because the optimiser may decide that the code will execute faster if it isn’t inlined.

The two things that are less likely to be inlined are non-item function pointer types (func: fn(&mut Item)) and calls made through virtual dispatch (func: &Fn(&mut Item)). Even then, you might get lucky.


#3

Thanks. I will use it more often then.