algorithm - swap two variables. which way is faster? -
let's have 2 integers , b. way faster swapping values?
c=a; a=b; b=c;//(edited typo)
or
a=a+b; b=a-b; a=a-b;
or bitwise xor
a=a^b; b=a^b; a=a^b;
i'll test performance differences when i'll able i'd know now. bitwise?
firstly, cannot quantify speed of algorithm independent of program language, compiler , platform on run. algorithm mathematical abstraction.
having said that:
- for typical programming language,
- and typical compiler, and
- a typical execution platform,
the first version typically faster because typically compile fewer native instructions take less clock cycles execute. first version requires load , save operations. other 2 versions have (at least) same number of loads , saves, , additional arithmetic or bit manipulation instructions.
however, not cut-and-dry.
the 2nd , 3rd examples performing swap without using temporary variable. might if using temporary variable expensive. might happen on machine didn't provide enough general purpose registers, , relative cost of loading / saving memory large. in circumstances, native code equivalents optimal.
however ... , real point ... best strategy leave kind of decision compiler. unless prepared put huge amount of effort micro-optimizing, compiler able better job can. indeed, writing code in "cunning ways" liable make harder compiler optimize. (in 3rd case example, compiler need figure out that sequence swapping 2 variables before can substitute optimal instruction sequence. chances optimizer won't able that.)
Comments
Post a Comment