Response.Write vs <%= %>

Jon P picture Jon P · Sep 30, 2008 · Viewed 70.3k times · Source

Bearing in mind this is for classic asp

Which is better, all HTML contained within Response.Write Statements or inserting variables into HTML via <%= %>.
Eg

Response.Write "<table>" & vbCrlf
Response.Write "<tr>" &vbCrLf
Response.Write "<td class=""someClass"">" & someVariable & "</td>" & vbCrLf
Response.Write "</tr>" & vbCrLf
Response.Write "</table>" & vbCrLf

VS

<table>
  <tr>
     <td class="someClass"><%= someVariable %></td>
  </tr>
</table>

I am mainly asking from a performance point of view in which will have the least server impact when there multiple variables to insert?

If there are no technical differences what are the arguments for one over the other?

Answer

Euro Micelli picture Euro Micelli · Sep 30, 2008

First, The most important factor you should be looking at is ease of maintenance. You could buy a server farm with the money and time you would otherwise waste by having to decipher a messy web site to maintain it.

In any case, it doesn't matter. At the end of the day, all ASP does is just execute a script! The ASP parser takes the page, and transforms <%= expression %> into direct script calls, and every contiguous block of HTML becomes one giant call to Response.Write. The resulting script is cached and reused unless the page changes on disk, which causes the cached script to be recalculated.

Now, too much use of <%= %> leads to the modern version of "spaghetti code": the dreaded "Tag soup". You won't be able to make heads or tails of the logic. On the other hand, too much use of Response.Write means you will never be able to see the page at all until it renders. Use <%= %> when appropriate to get the best of both worlds.

My first rule is to pay attention at the proportion of "variable text" to "static text".

If you have just a few places with variable text to replace, the <%= %> syntax is very compact and readable. However, as the <%= %> start to accumulate, they obscure more and more of the HTML and at the same time the HTML obscures more and more of your logic. As a general rule, once you start taking about loops, you need to stop and switch to Response.Write`.

There aren't many other hard and fast rules. You need to decide for your particular page (or section of the page) which one is more important, or naturally harder to understand, or easier to break: your logic or your HTML? It's usually one or the other (I've seen hundreds of cases of both)

If you logic is more critical, you should weight more towards Response.Write; it will make the logic stand out. If you HTML is more critical, favor <%= %>, which will make the page structure more visible.

Sometimes I've had to write both versions and compare them side-by-side to decide which one is more readable; it's a last resort, but do it while the code is fresh in your mind and you will be glad three months later when you have to make changes.