Ricardo Polo Jaramillo
Ricardo Polo Jaramillo

Reputation: 12318

What is the order of execution of the C# in Razor

I would like to understand the order of how Razor engine execute the c# code started with @.

I was trying to see the different times when the Controller is executed and the view is executed. So, I created this very simple ASP.NET MVC application. I store the time in a ViewBag variable in the Controller and show it the View, I also show the current time in the view.

The controller have this:

public ActionResult Index()
{
    ViewBag.ProcessingTime = DateTime.Now;
    return View();
}

The view have this:

Processing time: @ViewBag.ProcessingTime<br />

    @{
        int i = 0;
        do
        {
            i++;
            <text>@i<br /></text>
        }
        while (i < 1000000);
        }

Render time: @DateTime.Now 

The result is something like this:

Processing time: 03/03/2012 04:16:48 p.m.
1
2
3
4
[...]
999998
999999
1000000
Render time: 03/03/2012 04:16:48 p.m.

Why if it's clearly taking time to show me the webpage while it executes the if the ProcessingTime in the Controller and the RenderTime in the view is the same?

Upvotes: 0

Views: 1204

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Remember that the page is rendered on the server. So even if it visually to you it appears very slowly on the client (because you are sending a huge HTML), the actual rendering happens on the server and probably this happens in less than a second as all you do is to loop over 1 million elements.

Try showing the processor ticks and you should notice a difference (and if you don't there must be something fundamentally wrong):

Processing time: @ViewBag.ProcessingTime.Ticks

... your loops and stuff

Render time: @DateTime.Now.Ticks

So the actual execution is the following:

  1. The client requests /home/index.
  2. The controller action executes, stores the current time in the ViewBag and begins executing the view.
  3. The execution of the view is just looping and dumping 1M elements to the response stream which happens very fast, probably in less than a second. So when it reaches the last line of the view in less than a second or so, this last line is sent to the client.
  4. Lots of time (compared to the execution on the server) takes for this stream to reach the client.
  5. Lots of time (compared to the execution on the server) takes for the client to build a DOM tree and show it.
  6. At last the client shows the state of what was generated on the server which happened pretty fast.
  7. In your browser you observe pretty close times and yet lots of time happened between this page render in this browser.

Upvotes: 4

Related Questions