Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C#
Article

StringConc vs StringBuilder Test

Rate me:
Please Sign up or sign in to vote.
1.73/5 (8 votes)
17 Jan 20071 min read 27.5K   7   11
StringConc vs StringBuilder Test

Sample Image - StringConc_vs_StringBuild.gif

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:
C#
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);   //how many times
            string theString = txtTheString.Text;               //text to be used
            DateTime strCall = DateTime.Now;
            string targetString = null;
            for (int x = 0; x < iterations; x++)
            {
                targetString += theString;                      //concatenation using string concatenation 
            }
            TimeSpan time = (DateTime.Now - strCall);           //time needed for simple concatenation
            txtConcatTime.Text = time.TotalMilliseconds.ToString();

            //StringBuilder
            DateTime inCall = DateTime.Now;
            StringBuilder sb = new StringBuilder(theString);
            for (int x = 0; x < iterations; x++)
            {
                sb.Append(theString);                           //use of StringBuilder
            }
            time = (DateTime.Now - inCall);                     //time needed for StringBuilder to finish the job
            txtStringBTime.Text = time.TotalMilliseconds.ToString();
            MessageBox.Show("done");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UpdateTime();                                       //run the test
        }
    }
}


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.



License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Engineer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralStopwatch use Pin
zeltera28-Jan-07 7:30
zeltera28-Jan-07 7:30 
GeneralTotalMilliseconds is only accurate to 10ms Pin
GregMiller20-Jan-07 8:37
GregMiller20-Jan-07 8:37 
GeneralSource code missing Pin
TBermudez18-Jan-07 4:46
TBermudez18-Jan-07 4:46 
GeneralInaccurate Observation Pin
Mike Doyon18-Jan-07 2:27
Mike Doyon18-Jan-07 2:27 
Like others, I also agree that this is an inaccurate test for true optimization. Rather than debate what methods are more optimal and the reasons why (I think many are self explanatory), I'd rather provide you with a single piece of advice. When measuring for true perfomance, do not use "TimeSpan". Instead use "StopWatch". The StopWatch object gives you a more accurate measure (either ElapsedMilliseconds or ElapsedTicks).

By using a smaller time unit for measuring the time the routine took, you will see the marginal differences.

Just for fun, what do you think is more efficient when checking for an empty string?

if(myString==""){ perform xyz }
or
if(myString.Length==0) { perform xyz }

Is string.Length more efficient? Or is comparing it to an empty string more efficient? Or are they "about" the same? Try altering the loopct and watch the difference. Try measuring the elapsed time with "TimeSpan" instead of "StopWatch". You may be surprised...

FYI, on my pc (3.0ghz processor, 1gb ram) and a loop count of 1 billion (1000000000), one of the methods below takes about 11 seconds. You may consider dropping the loop count. The effects of the test are the same, but the measured time difference will be more marginal.

Here is the sample code to find out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace StringLengthEfficiencyTest {
public partial class Form1 : Form {
Stopwatch sw = new Stopwatch();
int loopCt = 1000000000;

public Form1() {
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) {
string s;
sw.Reset();
sw.Start();
for (int x = 0; x < loopCt; x++) {
s = "";
if (s.Length == 0) s = "";
}
sw.Stop();
label1.Text = "Length Check took " + sw.ElapsedMilliseconds.ToString();
}

private void button2_Click(object sender, EventArgs e) {
string s;
sw.Reset();
sw.Start();
for (int x = 0; x < loopCt; x++) {
s = "";
if (s == "") s = "";
}
sw.Stop();
label2.Text = "String Compare took " + sw.ElapsedMilliseconds.ToString();
}
}
}





Life should NOT be a journey to the grave with the intention of arriving safely in an attractive and well preserved body, but rather to skid in sideways, burger in one hand, drink in the other, body thoroughly used up, totally worn out and screaming "WOO HOO......What a ride!"

GeneralRe: Inaccurate Observation Pin
Jan Seda18-Jan-07 5:11
professionalJan Seda18-Jan-07 5:11 
GeneralNot correct Pin
Jan Seda18-Jan-07 1:02
professionalJan Seda18-Jan-07 1:02 
GeneralRe: Not correct Pin
zeltera18-Jan-07 1:08
zeltera18-Jan-07 1:08 
GeneralRe: Not correct [modified] Pin
Jan Seda18-Jan-07 1:30
professionalJan Seda18-Jan-07 1:30 
GeneralRe: Not correct Pin
Alois Kraus18-Jan-07 2:19
Alois Kraus18-Jan-07 2:19 
GeneralNot exact Pin
Itay Sagui18-Jan-07 0:23
Itay Sagui18-Jan-07 0:23 
GeneralRe: Not exact Pin
zeltera18-Jan-07 0:32
zeltera18-Jan-07 0:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.