Search code examples
c#performancevariablestimer

Efficiency: member variable vs local variable in a timer


I could not find similar questions here, so I am posting new one. In c# program with timer, what is more efficient:

  1. Declaring member variable, then using with each timer tick, it to calculate and change its value, or
  2. Declaring local variable inside a timer_tick routine, and declaring it each time, recalculating, using it, and then with next tick - doing it all over again ?

Example code:

ClassOne
{
    float mVar1 = 0;

    Timer_Tick
    {
        mVar1 += CurrentSpeed;
        SpeedOfSomething = mVar1;
    }
}

OR:

ClassOne
{
    Timer_Tick
    {
        float Var1 = 0;
        Var1 += CurrentSpeed;
        SpeedOfSomething = Var1;
    }
}

Solution

  • in the second one:

     Timer_Tick
        {
            float Var1 = 0;
            Var1 += CurrentSpeed;
            SpeedOfSomething = Var1;
        }
    

    Every time that Timer_Tick is fired, float Var1 = 0; will be executed and actually Var1 value will always be 0. So its not a correct solution.