most efficient way of swapping values c++

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


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.


In my case, std::swap is 5% slower than the following (both with O3 optimization). In general, std::swap() function calls copy constructor that will be probably always slower than just copy part of memory.

#include <cstring>

size_t objectSize = sizeof(Object);
char temp[objectSize];

loop {
    loop {
        memcpy(temp, a, objectSize);
        memcpy(a, b, objectSize);
        memcpy(b, temp, objectSize);
    }
}

Edit: Using stack instead of heap memory allocation.