Are they equal after complier optimization?

// buf_len: Option<usize>
let buf_len = buf_len.and_then(|n| Some(n * 1048576)).unwrap_or(16 * 1048576);
let buf_len = buf_len.unwrap_or(16) * 1048576;

If buf_len is None, the one above seems to be more efficient because the value of 16 * 1048576 is obviously already calculated at compile time. But the following one is much more natural and concise, and I would prefer to write the following one if the compiler can optimize it.

The assembly is the same.

and_then:
	shlq	$20, %rsi
	testq	%rdi, %rdi
	movl	$16777216, %eax
	cmovneq	%rsi, %rax
	retq
.set unwrap_or, and_then

Actually, you likely shouldn't have worried about this in the first place. Since you are referring to some sort of buffer, you are likely doing I/O. The cost of an integer multiplication is going to be dwarfed by any sort of I/O, by several orders of magnitude. Even if the compiler couldn't optimize the simpler code, it wouldn't even matter, because it wouldn't make your program even noticeably slower.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.