There are various ways to write such loops, e.g.
std::vector<int> v = ...;
for (size_t i = 0; i < v.size(); ++i)
{
...v[i]...
}
And with iterators:
std::vector<int> v = ...;
for(auto it = v.begin(); it != v.end(); ++it)
{
...*it...
}
Note: writing
it++
leads in general to worse results since some temp value must be stored first.
Assumed "instructions"
first case | second case |
---|
Load reg_i,0
Load reg_v,address_of_v
Load reg_begin,[v,begin]
Loop: Load reg_size,[v,end]
Sub reg_size,reg_begin
Cmp reg_size,reg_i
Branch_if_less_or_equal Endloop
...
Load reg_data,[reg_begin,reg_i]
...
; sizeof(int) == 4
Add reg_i,4
Branch Loop
Endloop:
... |
Load reg_v,address_of_v
Load reg_it,[v,begin]
Loop: Cmp reg_it,[v,end]
Branch_if_equal Endloop
...
Load reg_data,[reg_it]
...
; sizeof(int) == 4
Add reg_it,4
Branch Loop
Endloop:
... |
I tried to do a fair comparison. With the assumed "instruction set", the iterator based approach has two instruction less in the loop. Mainly the size calculation counts here.
So much for the intellectual challenge ;-)
Cheers
Andi