Moo
Moo

Reputation: 3675

Is using a getter in a for-each loop inefficient?

Recently I have been doing the following in my code:

for(auto& item : something.getSomeVector())

As I started my optimization pass, I started to wonder if that is less efficient than something like the following:

std::vector<Type> vTypes = something.getSomeVector();
for(auto& item : vTypes)

Would a for-each loop copy the vector or just keep calling that function?

Thanks!

Upvotes: 2

Views: 537

Answers (1)

M.M
M.M

Reputation: 141586

The definition of range-based loop is that your code expands to something very similar to this, inside a block:

auto && __range = something.getSomeVector();
auto __begin = begin(__range);
auto __end = end(__range);

for (; __begin != __end; ++__begin)
{
    auto &item = *__begin;

So as you can see, it is already optimal and your suggested improvement may even make things worse (if the function returned by reference then you made a copy where none was made previously).

Upvotes: 9

Related Questions