Response.Write
This ASP.NET method adds string
data to the Response buffer. With it, no intermediate conversions are needed. Developers often write text with Response.Write
.
We can improve Response.Write
calls to be faster. Use Response.Write
on each individual string
or character. If possible, avoid all concatenations.
Here we use Response.Write
, but append strings to pass as parameters. This is slower than necessary because the strings require copying and allocation.
// // A. Slow version (1568 ms) // foreach (var pair in _diskDictionary) { Response.Write(pair.Key + ":" + pair.Value.ToString() + Environment.NewLine); }
I tried eliminating the repeated Write calls and simply using a temporary StringBuilder
. I varied the capacity of the StringBuilder
, but this next code worked well.
// // B. Slower version (1614 ms) // StringBuilder builder = new StringBuilder(); foreach (var pair in _diskDictionary) { builder.Append(pair.Key).Append(":").Append( pair.Value.ToString()).AppendLine(); } Response.Write(builder.ToString());
Here I made a couple changes. I split up the Response.Write
calls to send one argument at a time and not concatenate anything beforehand. This was a substantial speedup.
// // C. Faster version (1474 ms) // foreach (var pair in _diskDictionary) { Response.Write(pair.Key); Response.Write(':'); Response.Write(pair.Value.ToString()); Response.Write(Environment.NewLine); }
Next we see a further improvement. I changed the newline to be a simple "\n" character. Environment.NewLine
is "\r\n" which is twice as long.
// // D. Fastest version (1318 ms) // foreach (var pair in _diskDictionary) { Response.Write(pair.Key); Response.Write(':'); Response.Write(pair.Value.ToString()); Response.Write('\n'); }
Here is another improvement. I looked carefully at the Response type in IL Disassembler, and it is accessed through a property. Properties are slower than local instances.
// // E. Faster than fastest version // HttpResponse r = Response; foreach (var pair in _diskDictionary) { r.Write(pair.Key); r.Write(':'); r.Write(pair.Value.ToString()); r.Write('\n'); }
ASP.NET works with the Response buffer. The best approach is to pass in each separate string
. This is faster, uses less memory, and even simpler to read.
We used the Response.Write
method for appending strings to the Response. We can call Response.Write
with individual string
arguments for the clearest and fastest code.