we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:
void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.
Depends on your compiler, processor architechture, how the turing complete
(?) system executing the code is configured and other factors someone might
kindly contribute. A neat trick but the possible speedup in a typical case
doesn't come from fact that this tiny fragment of code itself when compiled
to something is faster than what the other function would produce but rather
the fact that it might require one less register (assuming this turing
complete computing system has registers or some level of hierarchy as far as
accessing the variables is concerned speedwise) possibly reducing or
completely avoiding spilling (assuming that your computer and/or
microarchitechture and/or/maybe turing complete computing system and the
compiler implementation are related to the concept of spilling in any shape,
form, method, way or fashion).
Furthermore (insert previous disclaimers enmasse here for security reasons),
your compiler might implement these functions without linking time code
generation, leading to observation that the implementation uses some
fashion, form or equivalent of call/return instructions, or close
resemblance thereof concepts making the issue of avoiding spilling a moot
one from any practical point of view in terms of performance or size of the
compiled code. <- this paragraph makes some rather bold assumptions about
the state of the system you are querying the possible differences of
performance for.
However, you should not concern yourself with this level of optimization
very much as it is highly platform and compiler dependent. The fastest way
to do something is not to do it at all, if you can avoid computing
something: don't compute it. It may be faster overall to do relatively slow
operation only a few times rather than optimized operation many times. Use
std::swap and when it becomes apparent that it is too slow and actual
bottleneck in your application you might find out that no matter how fast
swap you have won't help either.. at that time you will be optimizing
something that actually matters.
I'm not saying it's not all good and beneficial, even sexy if you have the
world's fastest swap.. it's just that either of these two can be faster than
the other one..