Call method / function twice Vs. Save to a variable and call once

advertisements

I often come to this question when coding.

Which of the following examples is a better practice? I am aware that other factors will influence whether one or the other one is better. But in general, what are the advantages of one over the other.

if(object.getA().Value != null) {
    return object.getA().Value;
}
return null;

Vs.

string x = string.null;
x = object.getA().Value;
return (x != null) ? x : null;

Here is another similar example:

var a = object.method(x).Value;
var b = object.method(x).Key;

Vs.

var y = object,method(x);
var a = y.Value;
var b = y.Key;

In other words my question is:

Is it better to call a method twice and have one less variable? or Is it better to save it into a variable and call the method twice?

Of course if the method results in a lot of processing it might be smart to call it once, but for general cases where the method is not too demanding and the space of the variable is not too big, which one is better and why? or which are the advantages of one or the other?

The difference between them might not make a big difference but I am trying to find better practices and will like to hear the input of some experienced programmers.

Many thanks


Caching the value in a variable is a basic optimization (related to memoizing).

When it becomes truly necessary is if the second call to the function is on the stack a significant percent of the time.

For example, if that second call is on the stack 10% or 20% of the time, then that's how much overall time you can save by caching the first result.

You can keep doing things like that, until the code is as fast as possible.

If I can give an example, ages ago I worked on an app that had code like this:

if (!Done()){
  do some stuff
}
....
if (!Done()){
  do some other stuff
}

Since Done() was such a short, clean, and simple function to call, it got called a lot. Never mind that it did a lot including querying a ton of stuff from a DB and throwing most of it away. Stackshots found the problem instantly.