Friday, May 29, 2009

C# String vs StringBuilder

When we have to loop through a huge number of recordset to concatenate the results, we should use a stringbuilder as opposed to a string. The reason being, in C#, the String object is being truncated and recreated elsewhere in memory as opposed to the StringBuilder which stays in memory and does not gets recreated.

If the recordset is huge enough (say maybe more than 10 records), then the usage of a StringBuilder rather than plain old concatenation will result in a faster response time.

I had a text file that I was reading the results from (the text file had 7000 lines of records) and I suspected the textfile was the bottleneck to the application as it was taking over 60 seconds to execute. Apparently after some usage of:


DateTime currentSystemTime = DateTime.Now;
Debug.WriteLine("DB START: " + currentSystemTime);

I realised that the program was really slow when it was trying to concatenate the files to form an sql query string. So rather than doing this:

String insertionQuery = "";
insertionQuery = insertionQuery + String.Format("INSERT INTO [log] (mac, type, yearmth, dte, tme) VALUES ('{0}','{1}','{2}', '{3}', '{4}');",
logMac, logType, logIndex, logDate, logTime);

I did this:

StringBuilder insertionQuery = new StringBuilder();
insertionQuery = insertionQuery.Append(String.Format("INSERT INTO [log] (mac, type, yearmth, dte, tme) VALUES ('{0}','{1}','{2}', '{3}', '{4}');",
logMac, logType, logIndex, logDate, logTime));

Solved

No comments: