Performance-impact of empty Page_Load() methods - asp.net

When adding a new page or user control to an ASP.NET webforms application, the code-behind class contains an empty Page_Load() event handler:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have an existing web app, where many pages and controls still contain these empty event handlers (they are not used).
Question: Is there any performance impact due to these empty event handlers and should they therefore be removed from all pages and controls?
Please note: I'm not mainly (or not only) concerned about any runtime-overhead, due to the empty event handler being called. I also wonder about any overhead while the page (markup) is JIT-compiled (because the event handlers have to be wired up to the events - probably using some reflection code).
Update: there was no real answer so far, so I can't accept any of them.

AutoEventWireup is not done at the compile time. When it set to true, the runtime has to look for each of the page event handlers using Delegate.CreateDelegate method for this. Here is a great article which describes this behaviour: Inside AutoEventWireup.
There is a similar question here: What is the performance cost of autoeventwireup?

While the stack frame must be adjusted to enter and leave your method (and doing nothing) as opposed to simply calling the base implementation (in this case System.Web.UI.Page
), the performance impact is incredibly small and most likely unmeasurable so you should be fine.

I'm fairly certain Page_Load occurs whether it's there or not. Much like PreRender occurs, or Page_Init.
Removing it will do nothing for performance.

Related

Prevent rendering of user control

in our asp.net webforms application, we dynamically load usercontrols into placeholders. In order to retain changes across post-backs, our page-life-cycle is a little more complex than usual. We ALWAYS restore the previous control structure in pageInit in order to successfully load our viewstate. Only then do we clear the placeholder and load a new control into it.
This unfortunately means an entire life-cycle both for the old AND the new usercontrol, including server-side-processing of the old module's entire .ascx markup-file.
Now my question: Is there any possibility to minimize server-side processing of the old module, as it never gets sent back to the client (i.e. it's server-side rendering is completely unnecessary). What I'd ideally want to achieve is a sort of "light-weight" loading of a usercontrol, when it's only purpose is restoring vewstate information without it ever reaching the client.
The goal of the exercise is performance optimization.
Any hints, ideas or suggestions appreciated!
I have resolved code running in webcontrol lifecycle events of dynamically added controls by simply checking if the control was visible (http://msdn.microsoft.com/en-us/library/system.web.ui.control.visible.aspx)-
protected void Page_Load(object sender, EventArgs e)
{
if (this.Visible)
{
//Your code here
}
}
If you have any methods that aren't triggered by a page lifecycle event, and have to be triggered by a user action, such as-
protected void Button1_Click(object sender, EventArgs e)
{
//Do something
}
This can safely be left as is, the method code will not be run until the control is added to the page and the action is triggered.
Although the visibility check doesn't feel especially elegant, it's probably the best way to deal with auto wired events on dynamically loaded controls.

Page_Load or Page_Init

Let's take a really simple example on using jQuery to ajaxify our page...
$.load("getOrders.aspx", {limit: 25}, function(data) {
// info as JSON is available in the data variable
});
and in the ASP.NET (HTML part) page (only one line)
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="getOrders.aspx.cs" Inherits="getOrders" %>
and in the ASP.NET (Code Behind) page
public partial class getOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string lmt = Request["limit"];
List<Orders> ords = dll.GetOrders(limit);
WriteOutput( Newtonsoft.Json.JsonConvert.SerializeObject(ords) );
}
private void WriteOutput(string s)
{
Response.Clear();
Response.Write(s);
Response.Flush();
Response.End();
}
}
my question is
Should it be
protected void Page_Load(object sender, EventArgs e)
or
protected void Page_Init(object sender, EventArgs e)
So we can save some milliseconds as we don't actually need to process the events for the page, or will Page_Init lack of some sorting of a method by the time it is called?
P.S. Currently works fine in both methods, but I just want to understand the ins and outs of choosing one method over the other
Basic page life cycle will answer your question Full article : http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle.aspx
check same question answer : Page.Request behaviour
Either one would work, because you're essentially throwing out the page lifecycle by calling response.Clear() and response.End(). Technically you could even go as far as putting that code in prerender and it would work. By accessing the Response object you're basically going over the head of the page and cutting it off mid-stride so that you can perform a much simpler task.
I assume you simply do not want the page lifecycle at all and simply want to return JSON from this page? If so, I highly recommend implementing it as a Generic Handler (ashx). In this case you'd simply use context.Request["limit"] and context.Response.Write in your Process method. The benefit of doing this is that you don't have all the overheads of .NET preparing the page class and starting the page lifecycle, and are instead using a file intended for the task you're doing.
It is nice to understand the page lifecycle, as shown in other answers, but realistically you're not using it at all and you'd be better off moving away from the page class entirely.
Page life-cycle only has meanings in context of page elements (controls), so i don't see any differences in your case, since you don't have any other child controls in your page - this is totally irrelevant.
But here is the real question: if you don't have any rendering of html in your page (only data serialization), why you have choose to work with regular .aspx page?
Web service is ideal candidate for this scenario. And you'll be surprised how much performance improvement you'll gain in the end.
You can very well use the Page Init method. But if you have controls in your page and want to access any property of those controls then better to use the Page load event, but in your case you don't need to use page load event.
You can go through the Asp.Net Page Life cycle here to better understand which event to use.

Where should stuff be done in an ASP.NET page?

I'm very new to ASP.NET and, after beating my head on a few problems, I'm wondering if I'm doing things wrong (I've got a bad habit of doing that). I'm interested in learning about how ASP.NET operates.
My question is: Where can I find documentation to guide me in deciding where to do what processing?
As a few specific examples (I'm interested in answers to these but I'd rather be pointed at a resource that gives more general answers):
What processing should I do in Page_Load?
What processing should I do with the Load event?
What can I do in Page_Unload?
What order do things get done in?
When is each event fired?
What is the page life-cycle?
edit: this question might also be of use to some people.
The links posted by various folks are very helpful indeed - the ASP.NET page life cycle really isn't always easy to grok and master!
On nugget of advice - I would recommend preferring the overridden methods vs. the "magically" attached methods, e.g. prefer the
protected override void OnLoad(EventArgs e)
over the
protected void Page_Load(object sender, EventArgs e)
Why? Simple: in the overridden methods, you can specify yourself if and when the base method will be called:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// your stuff
}
or:
protected override void OnLoad(EventArgs e)
{
// your stuff
base.OnLoad(e);
}
or even:
protected override void OnLoad(EventArgs e)
{
// some of your stuff
base.OnLoad(e);
// the rest of your stuff
}
or even:
protected override void OnLoad(EventArgs e)
{
// your stuff
// not call the base.OnLoad at all
}
You don't have that flexibility in the Page_Load() version.
Marc
The first thing you need to learn to be able to understand the the questions you just asked is: PAGE LIFE CYCLE. It is a bitch sometimes, especially the ViewState part.
•What processing should I do in Page_Load?
•What processing should I do with the Load event? = Page_load
•What can I do in Page_Unload? Clean up
•What order do things get done in? PAGE LIFE CYCLE
•When is each event fired? PAGE LIFE CYCLE
•What is the page life-cycle?
Edit: Image source: http://www.eggheadcafe.com/articles/20051227.asp
More info: http://www.codeproject.com/KB/aspnet/PageLifeCycle.aspx
Here are some good links to get you started. Understanding how the ASP.NET life-cycle fits together is critical to understanding how your code will interact with it.
ASP.NET Page Life Cycle Overview:
When an ASP.NET page runs, the page
goes through a life cycle in which it
performs a series of processing steps.
These include initialization,
instantiating controls, restoring and
maintaining state, running event
handler code, and rendering. It is
important for you to understand the
page life cycle so that you can write
code at the appropriate life-cycle
stage for the effect you intend.
Additionally, if you develop custom
controls, you must be familiar with
the page life cycle in order to
correctly initialize controls,
populate control properties with
view-state data, and run any control
behavior code. (The life cycle of a
control is based on the page life
cycle, but the page raises more events
for a control than are available for
an ASP.NET page alone.)
The ASP.NET Page Life Cycle:
When a page request is sent to the Web
server, whether through a submission
or location change, the page is run
through a series of events during its
creation and disposal. When we try to
build ASP.NET pages and this execution
cycle is not taken into account, we
can cause a lot of headaches for
ourselves. However, when used and
manipulated correctly, a page's
execution cycle can be an effective
and powerful tool. Many developers are
realizing that understanding what
happens and when it happens is crucial
to effectively writing ASP.NET pages
or user controls. So let's examine in
detail the ten events of an ASP.NET
page, from creation to disposal. We
will also see how to tap into these
events to implant our own custom code.
ASP.net page lifecycle
I would definitely recommend you reading this:
http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp
If you're new to asp.net you'll have some trouble getting all of that, but really, I have yet to find such a detailed document on the topic comming from ms documentation or any ms employee blog.
I did it the hard way and followed every path I could using disassembled code but that guy really took the time to write it.
Basically try and do it in Page_Load and if that doesn't work, try it in either Page_Init or Page_Render. Normally one of them works :) That's the scientific approach.

How come the attributes for event handler properties on ASP.NET controls have a prefix (OnLoad for the Load event handler)

This is just for a better understanding of the ASP.NET framework. When you use a control in a declarative way (that would be web form markup), you assign event handlers by their method name using an attribute that starts with On:
<asp:Button runat="server" OnClick="..."/>
But when you look at the System.Web.UI.WebControls.Button class it has an EventHandler property named Click that the delegate is assigned to:
button.Click += new EventHandler(...);
So how is this implemented? Is that just a convention followed by the parser?
I know, it's a strange question, the answer will do nothing but satisfy my curiosity.
This is a naming convention used by ASP.NET which, rather unhelpfully, looks identical to another common naming convention widely used throughout .NET. Despite the apparent similarity, these two conventions are unrelated.
The .NET-wide convention, which turns out to be irrelevant here, is that it's common for events to have corresponding methods that raise the event, and for those methods' names to be formed by adding an On prefix to the event name. For example, the Click event offered by Button is related to an OnClick method, which raises that event (as has already been stated in another answer here).
The confusing part is that the OnClick method has nothing to do with the OnClick attribute that the question concerns.
It's easy to demonstrate that the OnSomeEvent methods are irrelevant here by writing a control that doesn't have any such method. Here's the codebehind for a simple user control:
public partial class EventWithoutMethod : System.Web.UI.UserControl
{
public event EventHandler Foobar;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Foobar != null)
{
Foobar(this, EventArgs.Empty);
}
}
}
This declares a Foobar event. (It never actually raises it, but that doesn't matter for the purposes of exploration.) It does not define an OnFoobar method. Nevertheless, ASP.NET is perfectly happy for us to use the OnSomeEvent convention when we use the control:
<user:EventWithoutMethod runat="server" OnFoobar="FooHandler" />
In fact, it's not only happy for us to do that, it actually requires it. Even though my control doesn't define any member called OnFoobar—the event is called just Foobar—I have to write OnFoobar if I want to attach the event handler from my .aspx file. If I just put a Foobar attribute in there in an attempt to attach the event, the handler will never run. (Unhelpfully, ASP.NET doesn't generate an error when you do that, it just silently fails to do anything with the attribute, and the event handler never runs.)

What does AutoEventWireUp page property mean?

I don't understand what the AutoEventWireUp page property is responsible for.
I've read through this article, but even that I don't understand.
When a Page is requested, it raises various events which are considered to be part of it's lifecycle. I keep the visual representation created by Peter Bromberg handy with me.
The AutoEventWireUp property when True, automatically wires up some of these built-in events in the Page life cycle to their handlers. This means that you do not need to explicitly attach these events (using the Handles keyword, for instance, in VB).
Examples of these built-in events would be Page_Init and Page_Load.
If you set AutoEventWireUp to True and provide explicit wiring up of the EventHandlers, you will find them being executed twice! This is one reason why Visual Studio keeps this attribute set to false by default.
Edit: (after Chester89's comment)
It is useful to note that the default value of the AutoEventWireUp attribute of the Page is true, while the default value of the AutoEventWireUp property of the Page class is false
To add to previous answers; the automatic hooks are applied from TemplateControl.HookUpAutomaticHandlers. This method calls into TemplateControl.GetDelegateInformationWithNoAssert which contains which methods are considered as event handlers.
These are, in System.Web, version 2.0:
On all classes deriving from Page: Page_PreInit, Page_PreLoad, Page_LoadComplete, Page_PreRenderComplete, Page_InitComplete, Page_SaveStateComplete.
On all classes deriving from TemplateControl: Page_Init, Page_Load, Page_DataBind, Page_PreRender, Page_UnLoad, Page_Error.`
Transaction support for all classes deriving from TemplateControl:
Page_AbortTransaction, or if it does not exist, OnTransactionAbort
Page_CommitTransaction, or if it does not exist, OnTransactionCommit
System.Web, version 4.0, introduced a Page_PreRenderCompleteAsync for all classes derived from Page. That method, if present, will be registered using Page.RegisterAsyncTask and executed automatically "just before the PreRenderComplete event" (source: Page.ExecuteRegisteredAsyncTasks). This method seems very undocumented which suggest that it would be prefered to just call Page.RegisterAsyncTask with your own method instead.
As mentioned in the article, if you have AutoEventWireUp turned on, asp.net will automatically recognize you have a method with the page_load syntax and call it automatically:
private void Page_Load(object sender, System.EventArgs e)
{
}
This gives you a cleaner code behind at the expense of some (very) small overhead. Notice that if you don't specify it you must explicitly tell asp.net you want to handle the page load event:
this.Load += new System.EventHandler(this.Page_Load);
Note that this applies to other events in the page, as it uses a naming convention as Page_Event.

Resources