mercredi 25 janvier 2017

Vector move constructor slower than copy constructor

I'm working on my first C++ project, which is a CSV parser (full source code here). It's at the point where it's working, and now I want to do basic refactoring / improve performance.

Currently the way the parser works is by returning each row as a std::vector<std::string>, and I figured that instead of allocating a new vector and a new string every time I'd just have an internal vector and internal string with reserved memory that I'd clear again and again.

That worked, and I started looking at other places where I might be doing memory allocation, and I saw this function which copies the internal vector, and then clears it:

auto add_row() -> std::vector<std::string> {
  auto row(m_bufvec);
  m_bufvec.clear();
  return row;
}

I figured that if I instead changed this line

auto row(m_bufvec);

to

auto row(std::move(m_bufvec));

It'd result in some sort of speed boost because according to http://ift.tt/1pUDKXt it would take constant time instead of linear. To my surprise, it made the parser significantly slower (according to my really rough benchmark of running time ./main.o over this file).

I'm completely new to optimization, benchmarking, and everything else that comes with tuning C++ code. Perhaps this optimization is useless even if it worked, but regardless, I'm curious as to why std::move causes a slowdown. Am I missing something?

Aucun commentaire:

Enregistrer un commentaire