« Fixed Size Memory Pool - 1 bit overhead!Upper to camel case constant/enum conversion macro »

Fast struct/class copy and exchange in C++

Sometimes you need to exchange (swap) two objects, or you need to copy objects without using their assignment operator nor copy constructor. Normally you would probably copy data using standard memcpy function. But in this case, memcpy can be really slow for such tasks, because not only that memcpy does several checks and calculations before actual copy operation, it's also designed to copy data of variable sizes. Plus it's not even inlined, so there's some overhead caused by calling the memcpy function itself.


Here's a fast and portable version of templated functions for object copy and exchange. It doesn't use memcpy or any other function, because it let's compiler to generate copy function by itself. Such copy function is pretty fast, compiler is able to perfectly optimize it and choose the best way how to copy the data. Usually, the final copy function is made only of several mov or rep movsd instructions.


template<typename Type>
inline void copyObject(Type& target, const Type& source)
{
    struct TempStruct {uint8_t data[sizeof(Type)];};
    *reinterpret_cast<TempStruct*>(&target) = *reinterpret_cast<const TempStruct*>(&source);
}

template<typename Type>
inline void exchangeObject(Type& a, Type& b)
{
    uint8_t t[sizeof(Type)];
    Type& c = *reinterpret_cast<Type*>(t);

    copyObject(c, a);
    copyObject(a, b);
    copyObject(b, c);
}

Released under WTFPL.


Happy coding!


Categories: Programming, Snippets

No feedback yet