I got baited by this r/rust post on Zig being faster than Rust, which is not the focus of this tidbit, rather this comment in the same post:
Try to change this:
let = (n as ).() as ; (3)...to:
let = (n as ).() as 1; (3)...just for fun and see what happens. The ..= range can be significantly slower than the .. range because in some cases it compiles to two separate comparisons instead of one. I don't know if it will make a difference in your case but I'm curious.
After a short excursion, I learned something new!
Inclusive ranges are slower compared to their equivalent exclusive range.
The inclusive range version requires doing additional checks since the upper bound may be the largest value for the integer type. Without the check, the iteration variable will overflow and cause an infinite loop, see also this comment by CAD1997. These checks also result in less optimization opportunities.
Rust
pub fn (: ) -> {
let mut = 0;
for _ in 1( 1) {
::::(1);
}
}
pub fn (: ) -> {
let mut = 0;
for _ in 1 {
::::(1);
}
}
Assembly
example::exclusive:
lea rax, [rdi - 1]
cmp rax, -3
ja .LBB0_1
xor eax, eax
lea rcx, [rsp - 8]
.LBB0_4:
mov qword ptr [rsp - 8], 1
add rax, qword ptr [rsp - 8]
dec rdi
jne .LBB0_4
ret
.LBB0_1:
xor eax, eax
ret
example::inclusive:
test rdi, rdi
je .LBB1_1
mov ecx, 1
xor eax, eax
lea rdx, [rsp - 8]
.LBB1_4:
mov rsi, rcx
cmp rcx, rdi
adc rcx, 0
mov qword ptr [rsp - 8], 1
add rax, qword ptr [rsp - 8]
cmp rsi, rdi
jae .LBB1_2
cmp rcx, rdi
jbe .LBB1_4
.LBB1_2:
ret
.LBB1_1:
xor eax, eax
ret
Benchmark
The benchmark was done using Criterion:
fn (: &mut criterion::Criterion) {
let mut = .benchmark_group("Iteration");
for in &[256, 512, 1024, 2048, 4096, 8192] {
.bench_with_input(
criterion::BenchmarkId::new("Exclusive", ),
,
|, | .iter(|| exclusive()),
);
.bench_with_input(
criterion::BenchmarkId::new("Inclusive", ),
,
|, | .iter(|| inclusive()),
);
}
.finish();
}
criterion::criterion_group!(benches, benchmark);
criterion::criterion_main!(benches);
And the output:
As you can see, the exclusive range version performs about twice as fast as the inclusive range version.