back_inserter and insert_iterator are very handy, but they’re also very inefficient!
When you’re appending chars, for example, there is a great deal of overhead for every element when you’re copying, when in many situations, there really doesn’t need to be.
Is there a way to make them more efficient?
Yes, you can define a new version of
std::copywhich can hijack optimizable calls. 🙂Below is an example (or "hack", if you prefer to see the glass half-empty) for Visual C++ and GCC.
On my personal computer (I use VC++ 2010), the code below makes calls ten times faster!
A benchmark for GCC’s is also here, showing a 5x difference: old version against new version
But before you use it:
Note that this code assumes the container provides a
vector-like interface.As currently written, this only works for C++11, because it uses the
type_traitsheader’s metaprogramming capabilities to only optimize those situations in which the copy operation would stay exception-safe.If you don’t need the exception safety (though you should think twice before actually doing this), or if you have another way of checking for such data types, then you can change
to:
and the rest of the code should work for C++03 as well.