Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a object which has a few base variables (integers as example) and one int

ID: 659015 • Letter: I

Question

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.

Explanation / Answer

It depends.

If you need to calculate once, and use million times, then the answer is obvious: the first case wins.

If you need to calculate every time, or quite often, then pick what you prefer. Your function doesn't read from a file, and has no slow operations, so it will not make a huge difference.

Avoid premature optimization.

When optimizing, it is best to measure. Profile the code and optimize only the bottlenecks. Everything else is a microoptimization, and should be avoided.