Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most efficient way of swapping values c++

I was wondering what the most efficient, in terms of operations, way of swapping integers is in c++, and why? Is something like:

int a =..., b = ...;
a = a + b;
b = a - b;
a = a - b;

more efficient than using a temporary? Are there any other more efficient ways? (not asking for just other ways to swap the ints) and why would they be more efficient?

like image 978
Mara Jade Avatar asked Feb 02 '16 13:02

Mara Jade


2 Answers

Assigning values is always faster than doing arithmetic operations.

C++ implementation for std::swap is

template<typename T> void swap(T& t1, T& t2) {
    T temp = std::move(t1); // or T temp(std::move(t1));
    t1 = std::move(t2);
    t2 = std::move(temp);
}

So to use a temporary variable is better than doing arithmetic trick.
And to use std::swap is even better because To reinvent the wheel in programming is never a good idea

like image 186
afzalex Avatar answered Oct 04 '22 00:10

afzalex


The best way is to trust your compiler and use the C++ standard library functions. They are designed for each other.

std::swap will win.

You could use an XOR swap for an int (which doesn't require a temporary), but these days it would still perform less well than std::swap.

like image 36
Bathsheba Avatar answered Oct 04 '22 02:10

Bathsheba