Only a few of these are actual programming tricks. The problem with sharing them is that they'll typically seem obvious to you, since you know them. It's difficult to know what is actually unknown to other people, and if you share stuff everybody knows you risk coming off as arrogant.
Here's one that I think more people should know: avoid branches. If I can do the same thing without an if statement and even a logical expression, the code typically both becomes easier to understand for people and easier to run for the CPU.
I'm struggling to comprehend how branches can be avoided (or why one would want to, as they are the cornerstone of programming). I can only think how to obfuscate them, which is rarely useful.
Here's an example of removing a branch that was posted to HN a little over a month ago: <a href="https://www.greyblake.com/blog/branchless-rust/" rel="nofollow">https://www.greyblake.com/blog/branchless-rust/
Yeah, I don't buy the premise that branchless code is intrinsically easier to understand. Maybe OP's point is that adding unnecessary branches makes code harder to read? But that's generally the case for any unnecessary code.
and skipping the if just makes the function shorter and simpler, while also not involving the CPU branch prediction. Another one that doesn't necessarily skip all branching but at least drops one - and more importantly makes the code simpler and easy to verify, is removing the if statement in code like
if (count == 0) {
return;
}
for (int i = 0; i != count; i++) {
puts("hello");
}
Both of your examples are optimized by the compiler (gcc 16.1 -O3).
In the first case, the compiler removes the first if/return
In the second case, if you don't have the first if/return the compiler will add it. That's because it will actually convert your loop into a do/while, with the test in the end, because it is more efficient. But it has to handle the count == 0 special case first, so it will do that early return even if it is not explicitly there.
That's the kind of optimization modern compilers are good at.
winternewt · · focus · HN ↗
Here's one that I think more people should know: avoid branches. If I can do the same thing without an if statement and even a logical expression, the code typically both becomes easier to understand for people and easier to run for the CPU.
cachvico · · focus · HN ↗
craftkiller · · focus · HN ↗
metabagel · · focus · HN ↗
jamiejquinn · · focus · HN ↗
robby_w_g · · focus · HN ↗
winternewt · · focus · HN ↗
GuB-42 · · focus · HN ↗
In the first case, the compiler removes the first if/return
In the second case, if you don't have the first if/return the compiler will add it. That's because it will actually convert your loop into a do/while, with the test in the end, because it is more efficient. But it has to handle the count == 0 special case first, so it will do that early return even if it is not explicitly there.
That's the kind of optimization modern compilers are good at.