Introduction
Because of the messages I received at one of my last article (
Meta Tag Generator) regarding the efficiency of using StringBuilder or String Concatenation I decided to write a short application to demonstrate that StringBuilder is efficient only if the number of concatenations is enough big (in this case bigger than 500).
Thanks also to:
http://channel9.msdn.com/ShowPost.aspx?PostID=14932
The code is very simple:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdateTime()
{
int iterations = Int32.Parse(txtIterations.Text);
string theString = txtTheString.Text;
DateTime strCall = DateTime.Now;
string targetString = null;
for (int x = 0; x < iterations; x++)
{
targetString += theString;
}
TimeSpan time = (DateTime.Now - strCall);
txtConcatTime.Text = time.TotalMilliseconds.ToString();
DateTime inCall = DateTime.Now;
StringBuilder sb = new StringBuilder(theString);
for (int x = 0; x < iterations; x++)
{
sb.Append(theString);
}
time = (DateTime.Now - inCall);
txtStringBTime.Text = time.TotalMilliseconds.ToString();
MessageBox.Show("done");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateTime();
}
}
}
How the test works:
in Iterations textbox write how many times do you want to "concatenate" the string from TheString textbox (it is not important how long is this text). Pressing the button Test you'll see the result (time needed to do the job with string conc (+=) and StringBuilder)
Case1: Iterations = 10 => ConcatTime = 0; StringBTime = 0;
Case2: Iterations = 100 => ConcatTime = 0; StringBTime = 0;
Case3: Iterations = 500 => ConcatTime = 2.05; StringBTime = 0;
Case4: Iterations = 1000 => ConcatTime = 15.52; StringBTime = 0;
Case4: Iterations = 10000 => ConcatTime = 3881.55; StringBTime = 0;
My Conclusion: if the numbers of concatenations is not bigger than 100, the run time is the same (zero). This means that is not important what method you use, or use the method you like more.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.