Skip to contentSkip to conversation

Improved Swaping Method In sort.c

DISCUSSION Soumyadip Das Mahapatra 3 participants 3 messages Apr 30, 2008

lore
Share & tools
lore
#1 lore raw
Quoted 1 line · Soumyadip Das Mahapatra

But this code saves memory equaling two integers. What about that ?

It won't because the compiler uses registers not memory for the temporary of course. In fact your version will cause more memory accesses because the compiler doesn't know that a and b do not alias each other, so it cannot cache the immediate value and has to always go through memory. The difference will not be large on x86 because L1 cache accesses are reasonably fast, but they're still much slower than a register access.

-Andi

#2 lore raw
In reply to Soumyadip Das Mahapatra
Quoted 9 lines · Soumyadip Das Mahapatra

Thanks Jan,
Actually it should be
static void u32_swap(void *a, void *b)

 {
    *(u32 *)b ^= *(u32 *)a;
    *(u32 *)a ^= *(u32 *)b;
    *(u32 *)b ^= *(u32 *)a;

}
But this code saves memory equaling two integers. What about that ?

The above prevents gcc from storing the intermediary in a register. So you're trading fast register access for slow memory access.

Really, you shouldn't be prosing optimizations unless you do two
things: check the output of gcc (on at least one platform, but really should be several), and include timings of before/after.