mercredi 20 février 2019

Why is a naive `iter_swap`potentially much slower than `swap`?

From David Abrahams and Aleksey Curtovoy's book "C++ Template Metaprogramming", I learned that iter_swap (see below) would be much slower than std::swap sometimes. Although the book has some explanation, I did not quite get it, could someone explains the reason behind it with more details.

template <typename ForwardIt1>
void iter_swap(ForwardIt1 it1, ForwardIt1 it2){
  typedef typename std::iterator_traits<ForwardIt1>::value_type T;
  T tmp = *it1;
  *it1 = *it2;
  *it2 = tmp;
}

template <typename ForwardIt1>
void swap_wrapper(ForwardIt1 it1, ForwardIt1 it2){
  std::swap(*it1, *it2);
}

By applying them on std::list<std::vector<std::string>>::iterator, I found the first is 10X slower than the second even when the size of the vector (whose elements are all small strings, length less than 10) is just 10.

Aucun commentaire:

Enregistrer un commentaire