Why is the following:
for (auto & x : vec) { /* do stuff with x */ }
faster than
for (int i = 0; i < v.size(); ++i) { /* do stuff with v[i] */ }
As my title said, I was told that incrementing and dereferencing the iterator faster than incrementing a separate variable and indexing it into the array, but don't understand why?
What exactly is happening that makes it faster?
I tried to step through and see what was happening and this is what I came up with
// pseudo instructions
// iterator
increment iterator
e.g., if the object is 3 integers you would increment the iterator
by 12
dereference this iterator
// pseudo instructions
// array
increment array index
add 1 to index counter
multiply by size of object
e.g., if the object is 3 integers, you multiply by 12
dereference the array
Iterating through an array seems rather trivial. You are just doing the following:
[offset + index * size] ; An array takes this form in assembly
Which would look something like this if you have an array of integers
[rbp - 16 + rdi * 4] ; rbp - 16 is the offset
; rdi is the index
; 4 is the size of the integer
The array iteration seems rather trivial, so I don't understand how dereferencing an iterator is faster.