Using of TextWriter by StringBuilder

Hi, today I want to share with you very simple idea of using correctly TextWriter class. You can imagine that TextWriter is created on the network stream solution in SOA (WCF), REST (WebAPI) or Web (ASP.NET) application. When you write to that stream very often you could have a lot of unnecessary round-trips between clients and server. But there is nice technique with StringBuilder I want to share with you in below tests. I think nothing more is needed for you than just look and compare results by yourself, but tests use MemoryStream without any network communication to make them simpler. You can use NetworkScream instead and test that idea solution by yourself. Enjoy!

namespace TextWriterSandbox
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;

    class Program
    {
        private static void Test01(int count)
        {
            TextWriter writer = new StreamWriter(new MemoryStream());
            for (var i = 0; i < count; ++i)
            {
                writer.WriteLine(i.ToString());
            }
            writer.Dispose();
        }

        private static void Test02(int count)
        {
            TextWriter writer = new StreamWriter(new MemoryStream());
            var buffer = new StringWriter();
            for (var i = 0; i < count; ++i)
            {
                buffer.WriteLine(i.ToString());
            }
            writer.Write(buffer.ToString());
            writer.Dispose();
        }

        private static void Test03(int count)
        {
            TextWriter writer = new StreamWriter(new MemoryStream());
            var buffer = new StringBuilder();
            for (var i = 0; i < count; ++i)
            {
                buffer.AppendLine(i.ToString());
            }
            writer.Write(buffer.ToString());
            writer.Dispose();
        }

        private static long Measure(Action<int> testAction, int count)
        {
            var meter = Stopwatch.StartNew();
            testAction.Invoke(count);
            meter.Stop();
            return meter.ElapsedMilliseconds;
        }

        private static void TestExecutor(Action<int> testAction, int count)
        {
            Console.WriteLine(
                "Name: {0} Count: {1} Milliseconds {2}",
                testAction.Method.Name, count, Measure(testAction, count));
        }

        static void Main(string[] args)
        {
            var count = 1000000;
            TestExecutor(Test01, count);
            TestExecutor(Test02, count);
            TestExecutor(Test03, count);
            Console.ReadKey(true);
        }
    }
}

p ;).

2 Replies to “Using of TextWriter by StringBuilder”

  1. Hi Paweł, of course you right, on prod code definitely is better to use using statement. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*