gareth618
gareth618

Reputation: 134

Performance of range-based for in C++

Let's say x is a vector<vector<int>> and I want to compute the sum of the sizes of each element of x. It's a stupid example, but I want to ask if the methods above are equivalent to performance when the sizes of the elements of x are enough big.

// The first method:
int sum = 0;
for (vector<int> it : x)
    sum += it.size();

// The second method:
int sum = 0;
for (vector<int>& it : x)
    sum += it.size();

I think the second for is faster because it uses &, so the values of each element of x aren't copied to it. Am I right or both methods perform the same?

Upvotes: 1

Views: 362

Answers (2)

Sneftel
Sneftel

Reputation: 41464

Yep, that's correct. Accidentally copying into a ranged for loop variable is a particularly common problem when one is using auto:

for (auto it : x)
     sum += it.size();

That's inefficient since, even when using auto to automatically set the type and even though the iteration is over a set of vector&s, it ends up having type vector. (The solution there would be auto&, or even better, auto const&.)

Incidentally, the main performance sink here would not just be the copying of elements from inside x to your temporary it, but the allocation and deallocation of the memory used by it.

Upvotes: 5

Nikos C.
Nikos C.

Reputation: 51832

Yes, the second for is faster. Quite a lot for large vectors. And it's very easy to bench it:

http://quick-bench.com/hR5VI3JwybDC0eBra6u8Ytd3uZ8

Benchmark result

Upvotes: 5

Related Questions