Can generic arguments reduce compile times?

Say that I have a function in a library that is not called by the lib itself.

pub fn my_func<I: IntoIterator<Item=i32>>(items: I) {
   // do a lot of work

Would having a generic argument lead to lesser compile times when a user of the library does not call this function?

Compared to this function for instance:

pub fn my_func(items: &[i32]) {
   // do a lot of work

Generic functions are slower than non-generic. They will be compiled in each crate using them, potentially multiple times. They will also bloat the executable, because there will be whole another copy of the function for every type it's used with.

That I do understand. I mean the case where they don't get materialized. So they are never called by a user.

If they're never used by anyone… that's an interesting case. I guess then it could be slightly faster, because the function is not given to LLVM.

Rust is not C++. Even if they are not materialized Rust does a lot of work to ensure they can be materialized safely.

That work is not free.

The only case where generic functions are guaranteed to be faster than non-generic is when one generic function replaces dozen of non-generic ones. And even then ratio where it becomes beneficial to use generic functions is not fixed: sometimes you may replace two non-generic functions with one generic and win, sometimes you need hundred functions before generic function would be faster.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.