Open

Description
This simple example of a naive factorial (n!
) implementation emits different code for using a range fold, and a loop over the iteration. Notably, the iterator fold emits many more instructions than the basic loop. This is unexpected, as this should be a zero-cost abstraction.
https://rust.godbolt.org/z/3cMMh67rE
type T = usize;
pub fn factorial1(n: u8) -> T {
let mut y = 1;
for k in 1..=n {
y *= T::from(k);
}
y
}
pub fn factorial2(n: u8) -> T {
(1..=n)
.map(T::from)
.fold(1, std::ops::Mul::mul)
}
@rustbot label I-heavy I-slow
Metadata
Metadata
Assignees
Labels
Area: Code generationCategory: An issue highlighting optimization opportunities or PRs implementing suchCall for participation: This issue needs bisection: https://github.com/rust-lang/cargo-bisect-rustcIssue: Problems and improvements with respect to binary size of generated code.Issue: Problems and improvements with respect to performance of generated code.Medium priorityRelevant to the compiler team, which will review and decide on the PR/issue.Performance or correctness regression from one stable version to another.