‹ 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. cestith · · focus · HN ↗
        Flow control is not always necessary. Other times it can be minimized. The point is not to never branch, but to avoid unnecessary ones.

        It&#x27;s not applicable to every situation, but one way to do this is some very basic fuzzy logic. You do a little math and then either choose a single branch at the end, or sometimes avoid a branch altogether. <a href="https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;artificial-intelligence&#x2F;fuzzy-logic-introduction&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;artificial-intelligence&#x2F;fuzzy-...

        Another way to avoid some branches is to have specialized routines, maybe with multiple dispatch, rather than more general methods with a bunch of checks within them for slightly different situations.

        A classic performance hack for critical sections is loop unrolling.

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.