Search code examples
c#filestreamstreamwriter

Using StreamWriter: What is quicker writting one big string or many smaller pieces?


I am generating an HTML output File in C#, though the speed performance for 60 Mb files seems to be impossibly long. It takes 20 minutes to generate the file, which is a very slow process. Previously around 35 Mb, it was generated in 5 Seconds, so I am not sure what is causing the delay here.

First I would be using these lines to start generating the report:

  public static void GenerateHtmlReport()
        {
            GenerateFinalResults();
            HtmlFileName ??= "Report-" + $"{DateTime.Now:dd_MMM_yyyy-[HH_mm]}" + ".html";
            var fileName = Path.Combine(GetRootFolder(), HtmlFileName);
            using var fs = new FileStream(fileName, FileMode.Create);
            using var w = new StreamWriter(fs, Encoding.UTF8);
            w.WriteLine(RenderHtml.ContructReportHeader(User));
            RenderHtml.ConstructHtmlBody(Results, w);
            w.WriteLine(RenderHtml.ConstructFullSummaryReport(Results));
            w.WriteLine(RenderHtml.ContructDashboard(Results, ResultStart));
        }

If I am writing to the file full string, then it takes fairly long, nevertheless writing it piece by piece, isn't really much more helpful I see.

Though this leads me to two questions

  1. Which process would be quicker, writing whole string or small pieces?
  2. is there a different file writing method I should use to speed up the performance?

Regards,


Solution

  • The answer indeed is the StringBuilder. Amending all parts of the code, instead of using + (concatenation) I sued StringBuilder.Append() and returned back it as a string. This is now creating the report in under 5 seconds instead of the 22 minutes. So it is a huge improvement.