Search code examples
c++performanceboostreverse

Is it better for performance to use boost::reversed than accessing back to front?


Is it better for performance to use boost::adaptors::reverse to access elements in a vector in reversed order instead of the usual v[i-1]?

I.E.:

std::vector<int> v {1,2,3,4};
for (const auto& el : boost::adaptors::reverse(v))
  print(el);

vs

std::vector<int> v {1,2,3,4};
for (size_t i = v.size(); i > 0; --i)
  print(v[i - 1]);

My logic would say that is not because reverse has to reverse the vector and then access it one by one and the usual way would load the vector piece in cache and then access the elements in reverse order. I guess that depending on the size of the vector one would be better than the other one, but I don't see why it would as a general rule.


Solution

  • reverse has to reverse the vector

    No, it's only an adaptor, it doesn't do anything to the vector. What it does is provide begin as the vector's rbegin, and end as the vector's rend. So these two pieces of code are more or less equivalent.