Reputation: 8747
Do views execute when returning the ActionResult
from the controller? Or is the ActionResult
just a reference to something which is executed later?
I have placed caching around some of the ActionResult
returns in my controller actions. Consider this, inside a controller action:
if(isCached(someKey))
{
return cachedActionResult;
}
else
{
var model = new ALazyLoadedModel();
return View(model);
}
So, after the first execution, the entire ActionResult
object is returned from cache. (That model has a bunch of lazy-loaded properties, so the "pain" of execution is when these properties get called out of the view. Thus, the execution of the model and the execution of the view are basically the same thing.)
However, performance gains haven't been all I hoped for, and when I put some timing around the creation of the model and the return of the view, it's apparently executing in fractions of a millisecond -- a Stopwatch
says that it takes just 0.0958 milliseconds to return (so, about 1/100,000th of a second). Based on what that model/view does, I find this a little hard to believe.
Here's what I suspect -- the return of the ActionView
doesn't actually execute the view, it just initializes the view and returns a reference to it, which is executed later. If this is true, then clearly this caching strategy won't help at all.
Is my suspicion right? Or does return View()
indeed execute the view and my view execution is apparently just a lot faster than I thought?
Upvotes: 0
Views: 296
Reputation: 78175
Yes, it is a central idea of ASP.NET MVC that the result of a controller's method is an intention to execute something, rather than a result of execution.
return View(model)
literally means telling to the framework, Please look up the view corresponding to this method being called, and render it using this model. All this work will happen outside of the controller's method, in the code that called it.
Upvotes: 1