473,543 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

stringBuilder vs string concatenation myth of usage...

Hi over there,
Propably this subject is discussed over and over several times. I did google
it too but I was a little bit surprised what I read on internet when it
comes 'when to use what'.
Most of articles I read from different experts and programmers tell me that
their "gut feelings" for using stringBuilder instead of string concatenation
is when the number of string concatunation is more then N ( N varies between
3 to max 15 from "different gut feelings"). Some are very specific, this
number (N) of concatenations should not pass never 7 !? Some of these
performance geeks are not far from my cube .....

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is between
100-200, there is no difference at all in milliseconds (and sometime no diff
in nanoseconds too).

The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10. (Amazing
even these tests had their loops number very very high from their
recommandations ....100'000)

Well I got the same results for loops less then 200 ! Am I missing something
or is just a fashion of coders to look "high-end performance Pros" ?????

Any input will be very much appreciated.

Thanks in advance,
Genc Ymeri
PS:
We are building a project that has many sql statements wich lines
(concatenations ) vary between 20-50. Personally I'm against of using .append
b/c it makes it harder to read through code but of course the performance
comes first if it makes a difference... With my test really shows that there
is no reall difference when this number is between 100-150.
Apr 11 '06 #1
33 4635
Hi,

Unless your application is performance-critical, then I'd stick with
the string concatenation and avoid using StringBuilder. I wouldn't
usually say that, but if you're constructing such complex dynamic SQL
queries then they're going to be much easier to read and maintain using
"+" rather than "Append()".

The difference in string performance will probably be negligible
compared with the execution time of your SQL query. If you're really
concerned about performance, maybe first look at converting your
dynamic queries into stored-procedures.

One final point, if you're building your queries in this way then make
sure you protect yourself from SQL injection attacks.

HTH,
Chris

Apr 11 '06 #2
I'd suggest also looking at your memory footprint. Performance tuning
is a lot more than just clock cycles. Find CLR profiler and watch your
heap usage in both instances. In the case of simple string
concatenation, you're going to end up creating N instances of the
string whereas in the StringBuilder case you're going to create far
fewer.

I've heard and abide by the rule: If the number of string
concatenations necessary is unknown (as is in your PS case) always use
StringBuilder, otherwise use discretion on your choice.

Apr 11 '06 #3
It isn't the time of processing that makes it important. It is the
allocation of memory. A string represents an immutable array of char. When
you change the size of a string, you actually must throw away the old array
of char and create a new one. Therefore, when doing a lot of concatenation,
you may be allocating quite a bit of memory. In the long run, it will be
disposed, but depending on the circumstances, it may cause a short-term
memory build-up that is unacceptable.

A StringBuilder, on the other hand, uses an internal array (buffer) in which
the characters are inserted. The length of the string is kept track of by
the object instance. So, you are not necessarily re-allocating memory when
appending or replacing parts of a StringBuilder.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

"genc_ymeri " <ge********@hot mail.com> wrote in message
news:au******** *************** *******@adelphi a.com...
Hi over there,
Propably this subject is discussed over and over several times. I did
google it too but I was a little bit surprised what I read on internet
when it comes 'when to use what'.
Most of articles I read from different experts and programmers tell me
that their "gut feelings" for using stringBuilder instead of string
concatenation is when the number of string concatunation is more then N
( N varies between 3 to max 15 from "different gut feelings"). Some are
very specific, this number (N) of concatenations should not pass never 7
!? Some of these performance geeks are not far from my cube .....

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is
between 100-200, there is no difference at all in milliseconds (and
sometime no diff in nanoseconds too).

The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10. (Amazing
even these tests had their loops number very very high from their
recommandations ....100'000)

Well I got the same results for loops less then 200 ! Am I missing
something or is just a fashion of coders to look "high-end performance
Pros" ?????

Any input will be very much appreciated.

Thanks in advance,
Genc Ymeri
PS:
We are building a project that has many sql statements wich lines
(concatenations ) vary between 20-50. Personally I'm against of using
.append b/c it makes it harder to read through code but of course the
performance comes first if it makes a difference... With my test really
shows that there is no reall difference when this number is between
100-150.

Apr 11 '06 #4
genc_ymeri <ge********@hot mail.com> wrote:
Propably this subject is discussed over and over several times. I did google
it too but I was a little bit surprised what I read on internet when it
comes 'when to use what'.
Most of articles I read from different experts and programmers tell me that
their "gut feelings" for using stringBuilder instead of string concatenation
is when the number of string concatunation is more then N ( N varies between
3 to max 15 from "different gut feelings"). Some are very specific, this
number (N) of concatenations should not pass never 7 !? Some of these
performance geeks are not far from my cube .....

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is between
100-200, there is no difference at all in milliseconds (and sometime no diff
in nanoseconds too).
100-200 sounds *way* higher than I've seen. Could you post your code?

Note that it depends on the *size* of the concatenations as well as the
number, and the distribution of those sizes.
The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10. (Amazing
even these tests had their loops number very very high from their
recommandations ....100'000)

Well I got the same results for loops less then 200 ! Am I missing something
or is just a fashion of coders to look "high-end performance Pros" ?????


It sounds like you may have been running the code under the debugger,
or something similar which could have skewed the results.

Of course, it's also possible that you're using .NET 2.0 and that the
tests were run under .NET 1.1... I haven't looked at whether things
have changed in that respect.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #5
Hi,

"genc_ymeri " <ge********@hot mail.com> wrote in message
news:au******** *************** *******@adelphi a.com...
Hi over there,
Propably this subject is discussed over and over several times. I did
google it too but I was a little bit surprised what I read on internet
when it comes 'when to use what'.
Most of articles I read from different experts and programmers tell me
that their "gut feelings" for using stringBuilder instead of string
concatenation is when the number of string concatunation is more then N
( N varies between 3 to max 15 from "different gut feelings"). Some are
very specific, this number (N) of concatenations should not pass never 7
!? Some of these performance geeks are not far from my cube .....
I think that it depends of sseveral factor like the size of each string and
the number of comparision, which is absolute faster in one particular
situation? Well you can always try both options in your particular situation
and decide.

I use strings for short concatenations, like the text of a
MessageWindow.S how or an event log entry when I usually concatenate no more
than 4 or 5 strings.

In a loop, always use StringBuilder.


So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is
between 100-200, there is no difference at all in milliseconds (and
sometime no diff in nanoseconds too).
IMO this number is WAY to big !!!
Can you post your code?

Also see this article:
http://msdn.microsoft.com/msdnmag/is.../CLRInsideOut/


PS:
We are building a project that has many sql statements wich lines
(concatenations ) vary between 20-50. Personally I'm against of using
.append b/c it makes it harder to read through code but of course the
performance comes first if it makes a difference... With my test really
shows that there is no reall difference when this number is between
100-150.


I would use StringBuilder , if well formatted the code is not that hard to
read.

Again, I think there is something wrong with your code
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Apr 11 '06 #6
Hi Jon
You really guessed it right :) about two things. (1) I ran it in debug mode
and (2) I have both .net frameworks installed in my machines. (Code was
writen with VS2003)

However switching from debug into release mode the result weren't that much
different.

I hope that everyone here doesn't get me wrong, I'm not saying string
concatenation is faster or the same compare with the stringbuilder
performance, as well the point is not how to get faster sql server results.
I'm trying to say that my testing show that there is almost no difference
for 100-200 string concatenations. So registering a javascript with 10-100
lines with stringBuilder all we really get is an uneasy source code to be
read. Same with sql statements....

Below is my testing code.

Thanks a lot,
Genc Ymeri.

PS:
Code I tested with:

private void btnStringPlus_C lick(object sender, System.EventArg s e)
{

int loops = Int32.Parse(tbx LoopNo.Text );
DateTime start = DateTime.Now;
string s = string.Empty;
for (int j = 0; j < loops; j++)
{
s += " hello ";

}

DateTime finish = DateTime.Now;

TimeSpan sp = finish - start;
lblResult.Text = string.Format( " {0} seconds and {1}
milliseconds",s p.Seconds.ToStr ing(), sp.Milliseconds .ToString());
lblResultNano.T ext = sp.Ticks.ToStri ng();

}
private void btnAppend_Click (object sender, System.EventArg s e)
{
int loops = Int32.Parse(tbx LoopNo.Text);

DateTime start = DateTime.Now;
StringBuilder sb = new StringBuilder() ;

for (int j = 0; j <loops ; j++)
{
sb.Append(" hello ");

}
sb.ToString();
DateTime finish = DateTime.Now;

TimeSpan sp = finish - start;
lblResult.Text = string.Format( " {0} seconds and {1}
milliseconds",s p.Seconds.ToStr ing(), sp.Milliseconds .ToString());
lblResultNano.T ext = sp.Ticks.ToStri ng();

}







"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
genc_ymeri <ge********@hot mail.com> wrote:
Propably this subject is discussed over and over several times. I did
google
it too but I was a little bit surprised what I read on internet when it
comes 'when to use what'.
Most of articles I read from different experts and programmers tell me
that
their "gut feelings" for using stringBuilder instead of string
concatenation
is when the number of string concatunation is more then N ( N varies
between
3 to max 15 from "different gut feelings"). Some are very specific, this
number (N) of concatenations should not pass never 7 !? Some of these
performance geeks are not far from my cube .....

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is
between
100-200, there is no difference at all in milliseconds (and sometime no
diff
in nanoseconds too).


100-200 sounds *way* higher than I've seen. Could you post your code?

Note that it depends on the *size* of the concatenations as well as the
number, and the distribution of those sizes.
The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10.
(Amazing
even these tests had their loops number very very high from their
recommandations ....100'000)

Well I got the same results for loops less then 200 ! Am I missing
something
or is just a fashion of coders to look "high-end performance Pros" ?????


It sounds like you may have been running the code under the debugger,
or something similar which could have skewed the results.

Of course, it's also possible that you're using .NET 2.0 and that the
tests were run under .NET 1.1... I haven't looked at whether things
have changed in that respect.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 11 '06 #7
> I use strings for short concatenations, like the text of a
MessageWindow.S how or an event log entry when I usually concatenate no
more than 4 or 5 strings
Thank you for posting back. I'm really glad to hear the opinion from someone
who uses stringbuilder for more than 5 string concatenations. I really want
to hear your opinion.

I just re-did a test with long lines (more than any screen today can show),
length=500 , loops = 100 and again it made no difference in performance at
all compare with stringbuilder for loops < 100. That tells me unless we want
to heavly manipulate strings or we have a long number of concatenations, in
our usual source code for easy sql statements or common string
concatenations for line with a length of the monitor, the "+" operator will
do the same job with the same cost.

Well, I'm not trying to let other known which is the most appropriate, I'm
just trying to get what are the benefits of using stringbuilder for
concatenation even for very long lines length = 500 when the loops < 100
??? Definately the performance can't be (I don't see any difference). yeah,
probably memory is better managed with the stringbuilder but performance
wise, I see no difference.

Is anything I'm missing still ??????
PS:
The line below is what I used for recent testing . It is concatenated 100
times with result +=s as well with string builder. No significant
performance gains.

s = "hello over there, this is test of string concatenation versus string
builder. Is worthy to use append for less than 100 lines ?hello over there,
this is test of string concatenation versus string builder. Is worthy to use
append for less than 100 lines ?hello over there, this is test of string
concatenation versus string builder. Is worthy to use append for less than
100 lines ?hello over there, this is test of string concatenation versus
string builder. Is worthy to use append for less than 100 lines"



well
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:u2******** ******@TK2MSFTN GP02.phx.gbl... Hi,

"genc_ymeri " <ge********@hot mail.com> wrote in message
news:au******** *************** *******@adelphi a.com...
Hi over there,
Propably this subject is discussed over and over several times. I did
google it too but I was a little bit surprised what I read on internet
when it comes 'when to use what'.
Most of articles I read from different experts and programmers tell me
that their "gut feelings" for using stringBuilder instead of string
concatenation is when the number of string concatunation is more then N
( N varies between 3 to max 15 from "different gut feelings"). Some are
very specific, this number (N) of concatenations should not pass never 7
!? Some of these performance geeks are not far from my cube .....


I think that it depends of sseveral factor like the size of each string
and the number of comparision, which is absolute faster in one particular
situation? Well you can always try both options in your particular
situation and decide.

I use strings for short concatenations, like the text of a
MessageWindow.S how or an event log entry when I usually concatenate no
more than 4 or 5 strings.

In a loop, always use StringBuilder.


So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is
between 100-200, there is no difference at all in milliseconds (and
sometime no diff in nanoseconds too).


IMO this number is WAY to big !!!
Can you post your code?

Also see this article:
http://msdn.microsoft.com/msdnmag/is.../CLRInsideOut/


PS:
We are building a project that has many sql statements wich lines
(concatenations ) vary between 20-50. Personally I'm against of using
.append b/c it makes it harder to read through code but of course the
performance comes first if it makes a difference... With my test really
shows that there is no reall difference when this number is between
100-150.


I would use StringBuilder , if well formatted the code is not that hard to
read.

Again, I think there is something wrong with your code
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Apr 11 '06 #8
genc ymeri <ge********@hot mail.com> wrote:
Hi Jon
You really guessed it right :) about two things. (1) I ran it in debug mode
and (2) I have both .net frameworks installed in my machines. (Code was
writen with VS2003)

However switching from debug into release mode the result weren't that much
different.

I hope that everyone here doesn't get me wrong, I'm not saying string
concatenation is faster or the same compare with the stringbuilder
performance, as well the point is not how to get faster sql server results.
I'm trying to say that my testing show that there is almost no difference
for 100-200 string concatenations. So registering a javascript with 10-100
lines with stringBuilder all we really get is an uneasy source code to be
read. Same with sql statements....
To me, that's an indication that you shouldn't have all that text in
your code to start with. Using a resource of some description would
usually make it easier to read and change.

As others have pointed out though, the impact of building the string is
going to be negligible compared with the time taken to execute the
query.
Below is my testing code.


Well, that's certainly not *all* of your testing code - it's a single
method. I note that it's also a method within a form, which can often
affect performance.

Now, about your code itself - that uses DateTime.Now, which has a very
coarse granularity. That's okay, so long as you make sure you test for
a long time - certainly longer than it would take to concatenate 100
strings. Here's a better test:

using System;
using System.Text;

class Test
{
static void Main(string[] args)
{
int iterations = int.Parse(args[0]);
int concatenations = int.Parse(args[1]);
string text = args[2];

int concatLength=-2;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
string tmp = "";
for (int j=0; j < concatenations; j++)
{
tmp += text;
}
concatLength = tmp.Length;
}
DateTime end = DateTime.Now;
Console.WriteLi ne ("Concatenat ion time: {0}", end-start);
}

int builderLength=-1;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
StringBuilder builder = new StringBuilder() ;
for (int j=0; j < concatenations; j++)
{
builder.Append( text);
}
builderLength = builder.ToStrin g().Length;
}
DateTime end = DateTime.Now;
Console.WriteLi ne ("StringBuil der time: {0}", end-start);
}
Console.WriteLi ne ("Lengths equal? {0}",
concatLength==b uilderLength);
}
}

Here are some results on my laptop, using .NET 1.1, compiling with
optimisation and running from the command line:

Iterations Concatenations Text += time StringBuilder timer
100000000 1 hello 05.547 16.234
100000000 2 hello 13.531 17.250
100000000 3 hello 23.625 20.984
100000000 5 hello 49.734 37.609
100000000 10 hello 1:59.250 1:11.781
10000000 100 hello 6:28.938 55.125

Now, this isn't a particularly in-depth test (in particular, it always
uses the same text), but it shows that the estimates of about 3-5
concatenations being the break-even point is reasonable - and by the
time we reach 100 concatenations, the difference is *proportionally *
significant. Now, that's very unlikely to make any absolute significant
difference when you're then going to a database, but there *is* a real
difference in the time taken *just for the string concatenation*.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #9
> So registering a javascript with 10-100 lines with stringBuilder all we really get is an uneasy source code to be read. Same with sql statements....

I take issue with your "easy to read" claim. Yes, in your test code,
that's true, but then I have little occasion to concatenate the same
string 100 times to create a long string. Are you really claiming that
this:

string sqlStatement = "select * from my_table where ";
sqlStatement += "field1='";
sqlStatement += value1.ToString ();
sqlStatement += "' and field2='";
sqlStatement += value2.ToSTring ();
sqlStatement += "'";

is easier to read than this:

StringBuilder sb = new StringBuilder(" select * from my_table where ");
sb.AppendFormat ("field1='{0}'" , value1);
sb.AppendFormat (" and field2='{0}'", value2);
string sqlStatement = sb.ToString();

? I would rather read the second version, myself.

Apr 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
4657
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie, 20-30k), what are the performance differences (if any with something as trivial as this) between initializing a new instance of StringBuilder with a...
4
2796
by: Lucas Tam | last post by:
Hi all, I'm concatenating a large SQL string for updating a table. There are > 80,000 commands (rows) in the SQL string. VB.NET seems to be *VERY* slow at string concatenation when the string gets large... Is it possible to execute a SQL command from a text file? .NET can streamwrite extremely fast so I was thinking of writing all the...
23
6213
by: Bonj | last post by:
what is the correct form of string concatenation in VB.NET, + or &? Both seem to work, but which is correct? I know it's + in C# and & in VB6, but which in VB.NET?
0
7399
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7584
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7729
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7677
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5258
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3386
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1809
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
952
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
626
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.