| Henri Korpela (43) | |
|
Hi, there! Yes, you read the title correctly. But why, you may ask now. Well, allow me to demonstrate: for(unsigned int i = 0; i < vector.size(); i++)As you can see, this is a basic for loop to iterate over elements of a vector. But did you know there's also a bit faster way to iterate over the elements, like this: for(unsigned int i = vector.size(); i--;)Yep, it works, but I'd like to go to even more extremes. Check out this piece of code: for(unsigned int&& i = vector.size(); i--;)But now the ultimate question is, does it work properly? | |
|
Last edited on
|
|
| Script Coder (348) | |
do you not mean:for(unsigned int i = vector.size();; i--)and for(unsigned int&& i = vector.size();; i--)
| |
|
|
|
| Caligulaminus (171) | |||
How would those loops end? | |||
|
|
|||
| Zephilinox (548) | |
| They don't, or at least if they do its implementation (un?)defined, subtracting 1 from an unsigned int of value 0 (i.e making it negative) sets it to its highest value on my system. | |
|
Last edited on
|
|
| Cubbi (1569) | |||||||||
Taking a look at gcc and clang as the most readily-available compilers, yes, there is an improvement in case of Clang, not as good as switching to iterators though. Iterators are what most people expect to see, and that's what the compilers optimize for.
It works properly, but it is exactly identical to your previous loop. Binding an rvalue reference to a size_t temporary doesn't involve anything that could be called "move semantics".
| |||||||||
|
Last edited on
|
|||||||||
| Henri Korpela (43) | |
|
Thank you for the replies! I didn't come to think of it that compilers would most likely optimize for loops this well. Assembly output convinced me. I'm trying to get the gist of move semantics, so that's why I was wondering, if declaring variable "i" as an rvalue reference had some performance gain. From what I can understand, GCC compiler does optimization best in the last test. No rvalue references required. Thanks a lot for the help! | |
|
|
|