C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Use Response.Write on each individual string or character. If possible, avoid all concatenations.
Version A: C#
//
// A. Slow version (1568 ms)
//
foreach (var pair in _diskDictionary)
{
    Response.Write(pair.Key + ":" +
        pair.Value.ToString() + Environment.NewLine);
}
Version B: C#
//
// 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());
Version C: C#
//
// 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);
}
Version D: C#
//
// D. Fastest version (1318 ms)
//
foreach (var pair in _diskDictionary)
{
    Response.Write(pair.Key);
    Response.Write(':');
    Response.Write(pair.Value.ToString());
    Response.Write('\n');
}
Response.Write method in ASP.NET performance
    20000 iterations.
Method A: 1568 ms
          Concats string parameter of Response.Write.
Method B: 1614 ms
          Appends data to StringBuilder than writes that.
Method C: 1474 ms
          Writes each part of data individually to Response.
Method D: 1318 ms
          Same as Method C except...
          Uses UNIX newline instead of Windows newline.
Method E: 1200 ms
          Stores HttpResponse as local variable.
          Only accesses Response property once.
          Is an estimate; was taken on different scale.
Tip: We can cache the Response object locally, and performance improves by nearly 10% in my benchmark.
And: The numbers I measured here were 748 before and 671 after, on a smaller data set.
Version E: C#
//
// 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');
}
Note: I have not carefully investigated this. Response.Write may have slower code for ints.
Tip: This is pretty obvious, but you don't want to use simple strings to build up output. This would involve the + operator.
Quote: Response.Write internally appends strings to a reusable buffer so that it does not suffer the performance overhead of allocating memory... (Improving ASP.NET Performance).