首页 > 编程 > .NET > 正文

回答讨饭猫之asp.net优化(一)

2024-07-10 12:58:11
字体:
来源:转载
供稿:网友

performance tuning tips

any programming model has its common performance pitfalls, and asp.net is no exception. this section describes some of the ways in which you can avoid performance bottlenecks in your code.
  1. disable session state when not in use: not all applications or pages require per-user session state. if it is not required, disable it completely. this is easily accomplished using a page-level directive, such as the following:
    <%@ page enablesessionstate="false" %>

    note: if a page requires access to session variables but does not create or modify them, set the value of the directive to readonly. session state can also be disabled for web service methods. see using objects and intrinsics in the web services section.
  2. choose your session state provider carefully: asp.net provides three distinct ways to store session data for your application: in-process session state, out-of-process session state as a windows service, and out-of-process session state in a sql database. each has its advantages, but in-process session state is by far the fastest solution. if you are only storing small amounts of volatile data in session state you should use the in-process provider. the out-of-process solutions are primarily useful in web garden and web farm scenarios or in situations in which data cannot be lost in the event of a server/process restart.
  3. avoid excessive round trips to the server: the web forms page framework is one of the best features of asp.net, because it can dramatically reduce the amount of code you need to write to accomplish a task. programmatic access to page elements using server controls and the postback event handling model are arguably the most time-saving features. however, there are appropriate and inappropriate ways to use these features, and it is important to know when it is appropriate to use them.
    an application typically needs to make a round trip to the server only when retrieving data or storing data. most data manipulations can take place on the client between round trips. for example, validating form entries can often take place on the client before the user submits data. in general, if you do not need to relay information back to the server, then you should not make a round trip to the server.
    if you are writing your own server controls, consider having them render client-side code for up-level (ecmascript-capable) browsers. by employing "smart" controls, you can dramatically reduce the number of unecessary hits to your web server.
  4. use page.ispostback to avoid extra work on a round trip: if you are handling server control postbacks, you often need to execute different code the first time the page is requested from the code you do use for the round trip when an event is fired. if you check the page.ispostback property, your code can execute conditionally, depending on whether there is an initial request for the page or a responce to a server control event. it might seem obvious to do this, but in practice it is possible to omit this check without changing the behavior of the page. for example:
        td.code {      padding:0,10,0,10;      border-style:solid;      border-width:1;      border-bottom:0;      border-top:0;      border-right:0;      border-color:cccccc;      background-color:ffffee    }    td.tab {      text-align:center;      font:8pt verdana;      width:15%;      padding:3,3,3,3;      border-style:solid;      border-width:1;      border-right:0;      border-color:black;      background-color:eeeeee;      cursor:hand    }    td.backtab {      text-align:center;      font: 8pt verdana;      width:15%;      padding:3,3,3,3;      border-style:solid;      border-width:1;      border-right:0;      border-color:black;      background-color:cccccc;      cursor:hand    }    td.space {      width:55%;      font: 8pt verdana;      padding:0,0,0,0;      border-style:solid;      border-bottom:0;      border-right:0;      border-width:1;      border-color:cccccc;      border-left-color:black;      background-color:white    }  
    <script language="c#" runat="server">    public dataset ds;    ...    void page_load(object sender, eventargs e) {        // ...set up a connection and command here...        if (!page.ispostback) {            string query = "select * from authors where firstname like '%justin%'";            mycommand.fill(ds, "authors");            mydatagrid.databind();        }    }    void button_click(object sender, eventargs e) {        string query = "select * from authors where firstname like '%brad%'";        mycommand.fill(ds, "authors");        mydatagrid.databind();    }</script><form runat="server">  <asp:datagrid datasource='<%# ds.defaultview %>' runat="server"/><br>  <asp:button onclick="button_click" runat="server"/></form>
    <script language="vb" runat="server">    public ds as dataset    ...    sub page_load(sender as object, e as eventargs)        ' ...set up a connection and command here...        if not (page.ispostback)            dim query as string = "select * from authors where firstname like '%justin%'"            mycommand.fill(ds, "authors")            mydatagrid.databind()        end if    end sub    sub button_click(sender as object, e as eventargs)        dim query as string = "select * from authors where firstname like '%brad%'"        mycommand.fill(ds, "authors")        mydatagrid.databind()    end sub</script><form runat="server">  <asp:datagrid datasource='<%# ds.tables["authors"].defaultview %>' runat="server"/><br>  <asp:button onclick="button_click" runat="server"/></form>
    <script language="jscript" runat="server">    public var ds:dataset;    ...    function page_load(sender:object, e:eventargs) : void {        // ...set up a connection and command here...        if (!page.ispostback) {            var query:string = "select * from authors where firstname like '%justin%'";            mycommand.fill(ds, "authors");            mydatagrid.databind();        }    }    function button_click(sender:object, e:eventargs) : void {        var query:string = "select * from authors where firstname like '%brad%'";        mycommand.fill(ds, "authors");        mydatagrid.databind();    }</script><form runat="server">  <asp:datagrid datasource='<%# ds.defaultview %>' runat="server"/><br>  <asp:button onclick="button_click" runat="server"/></form>
    c# vb jscript
    the page_load event executes on every request, so we checked page.ispostback so that the first query does not execute when we process the button_click event postback. note that even without this check our page would behave identically, since the binding from the first query would be overturned by the call to databind in the event handler. keep in mind that it can be easy to overlook this simple performance improvement when you write your pages.
  5. use server controls sparingly and appropriately: even though it is extremely easy to use, a server control might not always be the best choice. in many cases, a simple rendering or databinding substitution will accomplish the same thing. for example:
    <script language="c#" runat="server">    public string imagepath;    void page_load(object sender, eventargs e) {        //...retrieve data for imagepath here...        databind();    }</script><%-- the span and img server controls are unecessary...--%>the path to the image is: <span innerhtml='<%# imagepath %>' runat="server"/><br><img src='<%# imagepath %>' runat="server"/><br><br><%-- use databinding to substitute literals instead...--%>the path to the image is: <%# imagepath %><br><img src='<%# imagepath %>' /><br><br><%-- or a simple rendering expression...--%>the path to the image is: <%= imagepath %><br><img src='<%= imagepath %>' />
    <script language="vb" runat="server">    public imagepath as string    sub page_load(sender as object, e as eventargs)        '...retrieve data for imagepath here...        databind()    end sub</script><%--the span and img server controls are unecessary...--%>the path to the image is: <span innerhtml='<%# imagepath %>' runat="server"/><br><img src='<%# imagepath %>' runat="server"/><br><br><%-- use databinding to substitute literals instead...--%>the path to the image is: <%# imagepath %><br><img src='<%# imagepath %>' /><br><br><%-- or a simple rendering expression...--%>the path to the image is: <%= imagepath %><br><img src='<%= imagepath %>' />
    <script language="jscript" runat="server">    public var imagepath:string;    function page_load(sender:object, e:eventargs) : void {        //...retrieve data for imagepath here...        databind();    }</script><%-- the span and img server controls are unecessary...--%>the path to the image is: <span innerhtml='<%# imagepath %>' runat="server"/><br><img src='<%# imagepath %>' runat="server"/><br><br><%-- use databinding to substitute literals instead...--%>the path to the image is: <%# imagepath %><br><img src='<%# imagepath %>' /><br><br><%-- or a simple rendering expression...--%>the path to the image is: <%= imagepath %><br><img src='<%= imagepath %>' />
    c# vb jscript
    in this example, a server control is not needed to substitute values into the resulting html sent back to the client. there are many other cases where this technique works just fine, even in server control templates. however, if you want to programmatically manipulate the control's properties, handle events from it, or take advantage of its state preservation, then a server control would be appropriate. you should examine your use of server controls and look for code you can optimize.
  6. avoid excessive server control view state: automatic state management is a feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. this feature is not free however, since the state of a control is passed to and from the server in a hidden form field. you should be aware of when viewstate is helping you and when it is not. for example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case.
    viewstate is enabled for all server controls by default. to disable it, set the maintainstate property of the control to false, as in the following example:
    <asp:datagrid maintainstate="false" datasource="..." runat="server"/>

    you can also turn viewstate off at the page level. this is useful when you do not post back from a page at all, as in the following example:
    <%@ page maintainstate="false" %>
    note that this attribute is also supported by the user control directive. to analyze the amount of view state used by the server controls on your page, enable tracing and look at the view state column of the control hierarchy table. for more information about the trace feature and how to enable it, see the application-level trace logging feature.
  7. use system.text.stringbuilder for string concatenation: web applications often need to perform extensive string manipulation. although standard string operators work for concatenation, they have a negative impact on performance. using the system.text.stringbuilder class to concatenate strings provides better performance, as demonstrated by the following example:
    // using concatenation operators can sometimes produce// cleaner-looking code, but performance is not as good.string begin_query = "select upper(machinename) as machinename, "                   + "lower(machineowner) as machineowner, status, "                   + "starttime from net_stress where ";string end_query = " and starttime > '" + starttime + "' and starttime < '" + endtime + "'";string query = begin_query + getwhereclause("passed") + end_query;// consider replacing with stringbuilder instead:stringbuilder begin_query = new stringbuilder();begin_query.append("select upper(machinename) as machinename ");begin_query.append("lower(machineowner) as machineowner, status, ");begin_query.append("starttime from net_stress where ");stringbuilder end_query = new stringbuilder();end_query.append(" and starttime > '");end_query.append(starttime);end_query.append("' and starttime < '");end_query.append(endtime);end_query.append("'");string query = begin_query.append(getwhereclause("passed")).append(end_query).tostring();
    ' using concatenation operators can sometimes produce' cleaner-looking code, but performance is not as good.dim begin_query as string = "select upper(machinename) as machinename, " _                          & "lower(machineowner) as machineowner, status, " _                          & "starttime from net_stress where "dim end_query as string = " and starttime > '" & starttime & "' and starttime < '" & endtime & "'"dim query as string = begin_query & getwhereclause("passed") & end_query' consider replacing with stringbuilder instead:dim begin_query as new stringbuilderbegin_query.append("select upper(machinename) as machinename ")begin_query.append("lower(machineowner) as machineowner, status, ")begin_query.append("starttime from net_stress where ")dim end_query as new stringbuilderend_query.append(" and starttime > '")end_query.append(starttime)end_query.append("' and starttime < '")end_query.append(endtime)end_query.append("'")dim query as string = begin_query.append(getwhereclause("passed")).append(end_query).tostring()
    // using concatenation operators can sometimes produce// cleaner-looking code, but performance is not as good.var begin_query:string = "select upper(machinename) as machinename, "                   + "lower(machineowner) as machineowner, status, "                   + "starttime from net_stress where ";var end_query:string = " and starttime > '" + starttime + "' and starttime < '" + endtime + "'";var query:string = begin_query + getwhereclause("passed") + end_query;// consider replacing with stringbuilder instead:var begin_query:stringbuilder = new stringbuilder();begin_query.append("select upper(machinename) as machinename ");begin_query.append("lower(machineowner) as machineowner, status, ");begin_query.append("starttime from net_stress where ");var end_query:stringbuilder = new stringbuilder();end_query.append(" and starttime > '");end_query.append(starttime);end_query.append("' and starttime < '");end_query.append(endtime);end_query.append("'");var query:string = begin_query.append(getwhereclause("passed")).append(end_query).tostring();
    c# vb jscript

最大的网站源码资源下载站,

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表