Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading