dimanche 30 novembre 2014

Intermediate results as variables or only base values?


I have a object which has a few base variables (integers as example) and one intermediate variable for further processing. The intermediate variable can be calculated from the base vars. Now the question: Should I always repeat the calculation of the intermediate var from the base vars or should I save the value and only change it if the base vars change? (I need access to every var in pseudo random order.)


Two examples in C++-Code.


Caching the result:



class Test
{
private:
int a;
int b;
int c;

int x;

void calcX ()
{
// Just an example for a calculation for x.
x = ((a + 10) * (b / (c*c + 1)));
}

public:
void setA (int var)
{
a = var;
calcX();
}
void setB (int var)
{
b = var;
calcX();
}
void setC (int var)
{
c = var;
calcX();
}

// Every var has a get methode.
}


Always recalculating the result:



class Test
{
private:
int a;
int b;
int c;

int x;

public:
// Var a, b and c have get and set methodes.

int getX ()
{
return ((a + 10) * (b / (c*c + 1)));
}
}


So, which way is considered better? I really don't know. We should not save the intermediate value because it would be redundant, but then again we should not recalculate the value again and again.





Aucun commentaire:

Enregistrer un commentaire