2

I was wondering about the following situation in C#.

Sometimes function names can be quite long, and verbose. I'm using Microsoft's MVC 3 framework for a website at work, Here's an example function:

[ImportModelStateFromTempData]
[BreadCrumb("New Event")]
public ActionResult New()
{
    var @event = _dbContext.EventRepository.CreateNewEvent();

    return View("New", 
        EventViewModel.FromEventDomainModel(@event));
}

This code could be rewritten without use of the temporary variables @event, like so:

[ImportModelStateFromTempData]
[BreadCrumb("New Event")]
public ActionResult New()
{
    return View("New", 
        EventViewModel.FromEventDomainModel(_dbContext.EventRepository.CreateNewEvent()));
}

The first example is obviously more clear, but from a pure curiosity perspective/performance perspective, is either faster than the other? Especially considering that the cached value @event is only being used once.

In C++ I remember finding out that the local variable declaration of @event (if this were C++) would be stored in New()'s stack frame, and the assembly generated would be SLIGHTLY slower than directly in-lining the argument (as opposed to storing it in a temporary).

Is the C# compiler smarter about this situation? Am I free to use temporary's without the same performance considerations?

I understand that pre-optimization is evil, and I absolutely should not be worried about this kind of this, but I am curious about this. I'm not even sure about where I would go looking up more information about this, as the title was the best way I could describe my question. So what do you think Stack Overflow?

Short
  • 7,767
  • 2
  • 25
  • 33

2 Answers2

4

The IL produced by these will be equivalent. If you want to prove it to yourself, try compiling both and looking at the resulting IL with Ildasm http://msdn.microsoft.com/en-us/library/f7dy01k1(v=vs.80).aspx

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
3

Temporary variables are good.

When you are debugging, you can check the results of functions.

The delay, if there is one, is in nano or pico seconds.

Maintenance is king.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69