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 :

  • mov slower xor
  • test , jz used xor equality 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

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -