Skip to content

Example iterator fold vs. loop emit different code #99656

Open
@ghost

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

No one assigned

    Labels

    A-codegenArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-needs-bisectionCall for participation: This issue needs bisection: https://github.com/rust-lang/cargo-bisect-rustcI-heavyIssue: Problems and improvements with respect to binary size of generated code.I-slowIssue: Problems and improvements with respect to performance of generated code.P-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions