I was wondering if using a getter to get the same property over and over again in a loop has any performance hit. Should I save it to a variable first? Please see below examples:
Use getter directly:
for(int i=0; i<1000000; ++i) {
print("Phone = %d\n", myobj->getCity("Foo")->getPhone(i);
}
EDIT:
What about the loop constraint?
for(int i=0; i<myobj->totalPhoneNum(); ++i) {...}
or
int totalPhoneNum = myobj->totalPhoneNum();
for(int i=0; i<totalPhoneNum; ++i) {...}
Yes you should. Regardless of whether it makes any difference on performance it’s semantically clearer. By saving it to a variable first you indicate that it’s a loop invariant.