which one do you prefer? (of course getSize doesn’t make any complicated counting, just returning member value)
void method1(Object & o)
{
int size = o.getSize();
someAction(size);
someOtherAction(size);
}
or
void method2(Object & o)
{
someAction(o.getSize());
someOtherAction(o.getSize());
}
I know I can measure which one is faster but I want some comments… Not just executing time related… eg. if you are prefer method2, how many times maximally do you use o.getSize and what is the number what make you use method1 way?
Any best practices? (imagine even different types then int)
TY
I would go for method 1 not just because it’s probably marginally faster, but mostly because it means I don’t have to worry about whether the called method has any side effects.
Also, if this is called in a multi-threaded program this ensures that I’m always using my value of size – otherwise it might have changed between the two calls. Of course there may be cases where you explicitly might want to notice that change, in which case use method 2.
(and yes, per other answers, make
sizeaconst intto ensure that it’s not modified if it’s passed by reference to something else).