I’d like to know which solution could be faster. Let’s say we have mB vector of 100 (or n) pointers to objects of B that every each contains a foo() returning a double value:
Code 1:
int main () {
vector<double> mA;
for (int i=0; i<100; i++)
mA.push_back(mB->at(i)->foo());
for (int i=0; i<100; i++)
double a = pow((mA.at(i))*(mA.at(i+1)),2);
return 0;
}
Code 2:
int main () {
for (int i=0; i<100; i++)
double a = pow((mB->at(i)->foo()))*(mB->at(i+1)->foo())),2);
return 0;
}
Code 1 first store the double in a vector, so we have 100 calling to the functions by pointers and then 100+100 accessing to the vector mA. In the second, we have 100+100 calling to the functions by pointes.
1)Is the calling by pointer slower than an access .at() to a vector?
2) which soulution is it better for obtaining a faster code?
Thank you
Just looking at the code, the fact that the first snippet has 2 for loops that go to 100 and the second one has only 1 for loop, the first one would probably be slower.
The reason? If checks are super slow, and a for loop has a bunch of them. So, the first code snippet has double the amount of if checks. So, I don’t think the difference between both ways of accessing that you’re mentioning will play an important factor.
What you could try doing is look at the assembly generated by both, or you could use one of the many ways of timing functions. Since you have visual studio, you can try QueryPerformanceCounter:
http://support.microsoft.com/kb/815668
Try it and tell us the result!
PS. I suggested changing the title of your question, since you said “Velocity”, which would be incorrect, since you’re comparing speeds. Probably a better way of asking the question would be “which is faster, accessing… etc etc”, but I didn’t want to change it too much.