Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeated calling - coding practice

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

like image 580
relaxxx Avatar asked Apr 03 '11 08:04

relaxxx


3 Answers

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 size a const int to ensure that it's not modified if it's passed by reference to something else).

like image 79
Alnitak Avatar answered Nov 02 '22 23:11

Alnitak


Since you don't want size to change when you call someAction() or someOtherAction() (as it cannot when it is the return value of a function), consider:

void method3(const Object& o)
{
    const int size = o.getSize();

    someAction(size);
    someOtherAction(size);
}

getSize() may be simple, or it may be doing a costly calculation. Also, the size of o may be changed by another thread between your calls to someAction() and someOtherAction().

like image 45
Johnsyweb Avatar answered Nov 02 '22 22:11

Johnsyweb


I would prefer the first approach. Calling a function repeatedly doesn't seem good to me, especially if the returned value is same everytime. The first approach also avoids the overhead of calling a function repeatedly.

like image 41
Nawaz Avatar answered Nov 03 '22 00:11

Nawaz