Response.Write vs <%= %>

后端 未结 15 2698
我在风中等你
我在风中等你 2020-12-28 14:34

Bearing in mind this is for classic asp

Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via &l

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 15:00

    Leaving aside issues of code readibility/maintainibility which others have addressed, your question was specifically about performance when you have multiple variables to insert - so I assume you're going to be repeating something like your code fragment multiple times. In that case, you should get the best performance by using a single Response.Write without concatenating all of the newlines:

    Response.Write "
    " & someVar & "
    "

    The browser doesn't need the newlines or the tabs or any other pretty formatting to parse the HTML. If you're going for performance, you can remove all of these. You'll also make your HTML output smaller, which will give you faster page load times.

    In the case of a single variable, it doesn't really make a lot of difference. But for multiple variables, you want to minimise the context switching between HTML and ASP - you'll take a hit for every jump from one to the other.

    To help with readibility when building a longer statement, you can use the VBScript line continuation charcter and tabs in your source code (but not the output) to represent the structure without hitting your performance:

    Response.Write "" _
            & "" _
                & "" _
            & "" _
            & "" _
                & "" _
            & "" _
            & "" _
                & "" _
            & "" _
        & "
    " & someVar & "
    " & anotherVar & "
    " & andSoOn & "
    "

    It's not as legible as the HTML version but if you're dropping a lot of variables into the output (ie a lot of context switching between HTML and ASP), you'll see better performance.

    Whether the performance gains are worth it or whether you would be better off scaling your hardware is a separate question - and, of course, it's not always an option.

    Update: see tips 14 and 15 in this MSDN article by Len Cardinal for information on improving performance with Response.Buffer and avoiding context switching: http://msdn.microsoft.com/en-us/library/ms972335.aspx#asptips_topic15.

提交回复
热议问题