Swap (computer programming)

In C++, overloads are provided allowing std::swap to exchange some large structures in O(1) time.

Some classes may allocate memory in the constructor and deallocate it in the destructor, thus creating expensive calls to the system.

The Standard Template Library overloads its built-in swap function to exchange the contents of containers efficiently this way.

Some languages, like Ruby or Python support parallel assignments, which simplifies the notation for swapping two variables: This is shorthand for an operation involving an intermediate data structure: in Python, a tuple; in Ruby, an array.

A compare-and-swap instruction is even provided in some processor architectures, which compares and conditionally swaps two registers.

In any case, in practice this could not be implemented in separate processors, as it violates Bernstein's conditions for parallel computing.

It would be infeasible to keep the processors sufficiently in sync with one another for this swap to have any significant advantage over traditional versions.