Efficiency

In terms of memory efficiency, is it quicker to reference the size of a vector (or any member function of any template container) using the .size member function like this:
1
2
3
4
void function(vector<int>& data)
{
    for (int start = 1; start < data.size(); ++start){}
}

or would it be more efficient to store the size in a variable and then access that variable, as in:

1
2
3
4
5
6
void function(vector<int>& data)
{
int size = data.size();
    
    for (int start = 1; start < size; ++start){}
}

I suppose my question is, what exactly does "efficiency" entail? There are many times when I am writing algorithms/code that I get stuck on what would be "quickest." Pretty general question, I suppose I'm just looking for any guidelines I can follow while coding to make my code less superfluous.
> would it be more efficient to store the size in a variable and then access that variable

No. (Unless compiler optimizations have been suppressed.) std::vector<>::size() is const-correct and the compiler knows what is going on.
Last edited on
Topic archived. No new replies allowed.