Skip to content

Iter with step_by(2) performs slowly #59281

Closed
@wooleyra

Description

@wooleyra

Comparing the performance between these similar functions, the one that uses the iterator with the step_by(2) function performs significantly slower than the one using a traditional "while loop".

fn is_prime_iter(num: u32) -> bool {
    if num == 2 {
        return true;
    }
    if num % 2 == 0 {
        return false;
    }
    let mut is_prime = true;
    for i in (3..num).step_by(2) {
        if num % i == 0 {
            is_prime = false;
            break;
        }
    }
    is_prime
}

fn is_prime_loop(num: u32) -> bool {
    if num == 2 {
        return true;
    }
    if num % 2 == 0 {
        return false;
    }
    let mut is_prime = true;
    let mut i = 3;
    while i < num {
        if num % i == 0 {
            is_prime = false;
            break;
        }
        i += 2;
    }
    is_prime
}

Running the experimental cargo bench --all-targets produced the following results for me using the nightly-x86_64-unknown-gnu toolchain (1.35.0-nightly):

// benchmark value: 15485867
test tests::bench_is_prime_iter  ... bench:  26,813,870 ns/iter (+/- 337,054)
test tests::bench_is_prime_loop ... bench:  21,607,357 ns/iter (+/- 242,028)

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions