Original Post
Let''s say you have a vector, with maybe 2000 elements, each of a struct that has multiple members. A loop then goes through each 2000 elements and alters every member variable. An example (no meaning, just hypothetical:
The STL documentation says that a [] dereference takes constant time. I''m not sure what that means, does it mean it takes just O(1) or what? So I was wondering if code like this would optimize that loop in main:
Would simply setting a pointer to the current element in a vector and then using that pointer be quicker than using the [] operator on the vector?
This example may not matter that much but lets say you have a loop that accesses a member of a vector around 20 times.
http://roninmagus.hopto.org
acronymfinder.com - Find any acronym you need!
#include <vector>
using namespace std;
struct ABC
{
int a, b, c;
};
int main()
{
vector <ABC> myABC;
myABC.resize(2000);
for(int i = 0; i < myABC.size(); i++)
{
myABC[i].a ++;
myABC[i].b ++;
myABC[i].c ++;
}
return 0;
}
int main()
{
vector <ABC> myABC;
ABC * ptrABC;
myABC.resize(2000);
for(int i = 0; i < myABC.size(); i++)
{
ptrABC = &myABC[i];
ptrABC->a++;
ptrABC->b++;
ptrABC->c++;
}
return 0;
}