Closed
Description
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)