‹ BackHN Continuity

Thread

Small programming tricks

681 points · 294 comments · signa11

  1. winternewt · · focus · HN ↗
    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.

    1. cachvico · · focus · HN ↗
      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.
      1. craftkiller · · focus · HN ↗
        Here&#x27;s an example of removing a branch that was posted to HN a little over a month ago: <a href="https:&#x2F;&#x2F;www.greyblake.com&#x2F;blog&#x2F;branchless-rust&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.greyblake.com&#x2F;blog&#x2F;branchless-rust&#x2F;
        1. metabagel · · focus · HN ↗
          From the article:

          =====

          Should you go branchless?

          Most of the time, no. Branchless code is harder to read and easier to get wrong. Besides, compilers know a lot of tricks and already do a lot of this work for us.

          Only when a profiler points at a hot loop, and the loop contains a branch on unpredictable data this technique can pay off big.

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.