Thursday, August 9, 2012

c# - String.Format vs String.Join Performance

In one of my projects,I parse a huge raw text file (160+ GB) and create a delimited  text output file.I have always used String.Format for writing to the output file till I came across String.Join.After going through the forums regarding both the method's performance,I decided to test it myself

Here are the test results.I ran this test all day long, multiple times.

String.Join is faster but the difference is negligible. Also note that these tests may vary based on your data,requirements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StringFormatJoin

{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);
                    Console.WriteLine(string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test"));
                }
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts.Hours, ts.Minutes, ts.Seconds,
                    ts.Milliseconds);

                Stopwatch stopWatch1 = new Stopwatch();

                stopWatch1.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);
                    Console.WriteLine(string.Join("|", new string[] { "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test" }));
                }

                stopWatch1.Stop();

                TimeSpan ts1 = stopWatch1.Elapsed;

                string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts1.Hours, ts1.Minutes, ts1.Seconds,
                    ts1.Milliseconds);

                Console.WriteLine("Format RunTime " + elapsedTime);

                Console.WriteLine("Join RunTime " + elapsedTime1);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

Output


Iterations:100,000




 Iterations:100,000



Iterations:1,000,000


Iterations:1,000,000




No comments: