Why does std::fs::write(…) use an inner function?

Monomorphization costs.

write(), like most filesystem functions in Rust, takes AsRef<Path> instead of Path, for convenience (to allow you to pass e.g. a &str). But that also has a cost: it means that the function will be monomorphized and optimized separately for each type, while there is no real need for that. While it is very likely that LLVM will deduplicate all those instances, the time used for optimizing them is still wasted compile time.

To mitigate this cost, it calls an inner, non-generic function that does all the heavy lifting. The outer function contains only the necessarily-generic code – the conversion to Path.

Leave a Comment