Software That Shines

Better Software Blog

Software Insights

Write what you mean!

In code, I'm a firm believer in "writing what you mean": writing simple, straightforward code instead of trying to be clever ("Being clever usually isn't").  It's probably less likely to let subtle bugs slip through, and not only is it easier for the person who comes after you to understand it (and that might be "you from the future"), but as it turns out, it's also often easier for the compiler to understand it, as illustrated in a recent post from Raymond Chen's invaluable blog, The Old New Thing.

[What's the fastest way to write a comparison?
The answers ranged] from the straightforward

int compare1(int a, int b)
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;

to the clever

int compare2(int a, int b)
    return (a > b) - (a < b);

to the hybrid

int compare3(int a, int b)
    return (a < b) ? -1 : (a > b);

to inline assembly

int compare4(int a, int b)
    __asm__ __volatile__ (
        "sub %1, %0 \n\t"
        "jno 1f \n\t"
        "cmc \n\t"
        "rcr %0 \n\t"
        "1: "
    : "+r"(a)
    : "r"(b)
    : "cc");
    return a;

Turns out, the compiler optimized the simplest, most straightforward version (the first one) into better assembly than even the hand-tuned fourth version.

Something something premature optimization…

Of course that doesn't mean you should be sloppy or can avoid putting careful thought into what you're doing (for example, the choice of IList vs HashSet vs IEnumerable is one I too-often don't see thought through).  Plenty more on that here: