Hacker News new | ask | show | jobs
by swingline-747 2821 days ago
Btw, XOR swap... probably slower than register-aliased swap, but it swaps two registers without using a third:

    void swap(char *s, int a, int b)
    {
       s[b] ^= s[a];
       s[a] ^= s[b];
       s[b] ^= s[a];
    }
2 comments

Most compilers will optimize this to whatever is faster even if you use the clearer version.
You're making a sweeping, laughably-false assertion. Clearly you don't understand how compilers work. C compilers are not miraculous magic boxes. They have limited information and limited optimizations. It's very likely an obscure implementation of an algorithm will more-or-less translate one-to-one to nearly equivalent assembly because the compiler can't analyze it.
I think you've misrepresented what I said, which was that the compiler is good enough to pick between a register or XOR-swap (in the comment I was replying to), based on the architecture and calling sites.
The "Clearly you don't understand how compilers work" portion of this comment is unnecessary.
You'd better hope that a!=b
Edge-case FUD.
Why would a==b be a problem with the XOR swap trick?

  function xorSwapTest(min, max) {
    for (var i = min; i < max; i++) {
      var a = i, b = i;
      b ^= a;
      a ^= b;
      b ^= a;

      if (a != i || b != i)
        throw Error("Problem with " + i);
      }

    return true;
  }
The issue is that if a == b, &s[a] == &s[b]; i.e. you're writing to the same address.