Talk:Developers Notebook-Tricks

From WxWiki
Jump to navigation Jump to search

'lo there, =)

just stumbled across the wx Developers Notebook-Tricks Wiki and felt like a had to shed a light on something:

* 1 Tricks of the Trade
    o 1.1 Swapping Values Without A Temporary Value
...
Original

inline void wxSwap (size_t& x, size_t& y)
{
	size_t z = x;
	       x = y;
	       y = z;
}
...
Faster, Modified

inline void wxSwap (size_t& x, size_t& y)
{
	x = x ^ y;
	y = x ^ y;
	x = x ^ y;
}

I'm afraid the original is not only the more versatile (if using templates), but also the faster (and - binary wise - shorter) version. ;-}

What you have here is a typical case of optimizing the debug code! Yes, you save a temporary and the whole thing is faster in the debug code, but a "moderately" good compiler will create better release code for the original version under most (all?) circumstances. Nearly all processors have some kind of "swap" (eXCHanGe) instruction. So the compiler will see that the temporary isn't really being used any further and serves only to swap values. It will then replace it by a swap instruction or eliminate it completely. The later can be the case when the code is being inlined and the compiler notices, for instance, that there is a temporary "hanging in" - in other words the swap can be omitted altogether. Furthermore (although being a nice example of what you can do with an "exclusive or" => cryptography), many of today's processors do some optimizations themselves. Using "register renaming" they can eliminate such a swap quite often or run it in parallel (pipelined). Your "faster version" cannot be optimized. Both compilers and processors will fail to see what is really happening. As a result you will have three "XOR" instructions depending on each other. So, while an "XOR" seems cheap at first glance it actually becomes more expensive (both in size and speed) than the original version. Needless to say (and I do it anyhow - see "Laurence Sterne" for dispensable penmanship;-) that the original version (template) can also swap doubles and entire objects. Again, most processors can swap doubles themselves and the compiler might be able to eliminate the whole thing in some (many) cases (especially fruitful when swapping big objects - which you shouldn't do in the first place).

Long story short: please keep the original version (template). ;-)

LC ([email protected])