How fast is std::swap for integer types?

前端 未结 4 1715
谎友^
谎友^ 2021-01-07 19:45

STL implements a generic std::swap function to swap 2 values. It can be presented in the following way:

template  void swap (T&am         


        
4条回答
  •  青春惊慌失措
    2021-01-07 20:17

    XOR swap is really only a gimmick and can fail in certain cases (e.g. both variables are references to the same object).

    XOR swap is also not particularly efficient as it has serial dependencies so it will always take at least three instruction cycles. Using a straightforward swap with a temporary has fewer dependencies, allowing for some parallelism on modern superscalar CPUs - on some CPUs it can even be implemented in one instruction, but even without special instructions it may well execute in two cycles.

提交回复
热议问题