Reputation: 363
As I know, declaration of variables of POD types or primitive types inside loops is OK (no overhead).
How about reference variables?
Does it matter to performance, to declare reference variables inside loops?
For example, a variable references to a vector, like below:
vector<vector<int> > data (100, vector<int> (100));
for (int i = 0; i < 100; ++i) {
vector<int> &row = data[i];
...
}
There will be no overhead, right?
Thank you.
Upvotes: 0
Views: 1939
Reputation: 9071
There should be no overhead because a reference is basically a memory location.
In a 32-bit application, a memory location is 4 bytes, so declaring that thing inside the loop has the same overhead as declaring an int
: negligible.
Upvotes: 0
Reputation: 13196
From a performance standpoint, references are as computationally complex as pointers (and typically are implemented internally in the same way).
Initializing the reference itself has no more overhead then initializing a pointer.
Though, based on your use case, you would probably find it easier and equally efficient (if slightly more verbose) to use an iterator.
vector<vector<int> > data (100, vector<int> (100));
for (vector<vector<int> >::iterator row = data.begin(); row != data.end(); ++row) {
// (*row)[0] = 1;
}
Upvotes: 1