Q:

C# DateTime stack memory

1) DateTime.Now returns a new DateTime instance.
2) DateTime.Subtract returns a new TimeSpan instance.
3) DateTime is a structure so occupies memory in the stack.
4) When a method exits (returns), its stack memory is reclaimed.
Therefore, does the following code save memory (assuming StartTiming method is in the same class containing Main)?
Code 1:

static Main(){

bool started = true;
static TimeSpan totalTime = TimeSpan.Zero;
static DateTime startTime = DateTime.Now;

while(started){
        // my assumption: every time the method is called, the same memory 
        // in the stack will be reused
        StartTiming();
    }
}

void StartTiming(){
     totalTime = DateTime.Now.Subtract(startTime);   
}

compared to the following code
Code 2:

static Main(){    

bool started = true;
TimeSpan totalTime = TimeSpan.Zero;
DateTime startTime = DateTime.Now;

while(started){
     // my assumption: every time this stmt is executed  DateTime.Now 
     // creates a new DateTime instance and Subtract creates a timespan instance
     totalTime = DateTime.Now.Subtract(startTime);
    }

}

A:

You will probably find that the StartTiming() method in Code 1 has been inlined by the JIT compiler so both versions produce same machine code.
What is more, since the method doesn't take any parameters no stack is used.
And what you are probably doing is a premature optimisation... ;-)

