algorithm - Swapping Integers Efficiency -
simply,
x = integer y = integer z ( if used ,integer temp ) what's efficient method ?
method :
z = x x = y y = z method ii :
x ^= y y ^= x x ^= y edit i [ assembly view ]
method :
mov mov mov method ii :
test ( , ) jz xor xor xor notes :
movslowerxortest,jzusedxorequality safe- `method uses register
in cases, using temporary variable (usually register @ assembly level) best choice, , 1 compiler tend generate.
in practical scenarios, trivial swap algorithm using temporary register more efficient. limited situations in xor swapping may practical include: on processor instruction set encoding permits xor swap encoded in smaller number of bytes; in region high register pressure, may allow register allocator avoid spilling register. in microcontrollers available ram limited. because these situations rare, optimizing compilers not generate xor swap code.
http://en.wikipedia.org/wiki/xor_swap_algorithm
also, xor swap implementation fails if same variable passed both arguments. correct implementation (from same link) be:
void xorswap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } } note code not swap integers passed immediately, first checks if addresses distinct. because, if addresses equal, algorithm fold triple *x ^= *x resulting in zero.
Comments
Post a Comment