By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,432 Members | 795 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,432 IT Pros & Developers. It's quick & easy.

String and StringBuilder

P: n/a
Hi all,
I know it is better to handle large string with a StringBuilder, but how
does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
Jul 31 '06 #1
Share this Question
Share on Google+
26 Replies


P: n/a
Hardy,

It works by preallocating a buffer which is added to. Instead of
allocating memory for the new string on concatenations, it has a buffer
pre-allocated which is written to. When the buffer is full, it then
reallocates the buffer to be twice as big, and copies the old buffer to the
new one.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Jul 31 '06 #2

P: n/a
Thanks, it makes sense to me!

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote in
message news:%2****************@TK2MSFTNGP04.phx.gbl...
Hardy,

It works by preallocating a buffer which is added to. Instead of
allocating memory for the new string on concatenations, it has a buffer
pre-allocated which is written to. When the buffer is full, it then
reallocates the buffer to be twice as big, and copies the old buffer to
the new one.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy


Jul 31 '06 #3

P: n/a
In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because strings are
immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs

StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();

each of the operations in the first loop create a new string as strings are
immutable (they cannot (well atleast in the safe world) be changed)... the
string builder continues using the same buffer. Since the string builder
uses the same object over and over (alterring an internal buffer) it will
use far less memory than the string example. The major speed gain is
realized in garbage collection and in the copying of memory ...

Creating objects in .NET is very fast, it is getting rid of them that is
slow .. since the first example creates so many intermediate objects the
garbage collector has alot of work to do to get rid of them.

For copying of memory the string example is basically copying the data for
the entire size of the string everytime a new string is created (for small
data sets this is rather minor but for big strings it gets quite expensive).
The StringBuilder class will also copy data if it has to expand its buffer
but will generally only have to copy the data that is actually being
appended (as opposed to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Jul 31 '06 #4

P: n/a
Hello Hardy,

Just to add to Nicholas, default buffer allocated by StringBuilder is for
16 symbols, afaik, after u used its size SB double its

HWHi all,
HWI know it is better to handle large string with a StringBuilder,
HWbut how
HWdoes StringBuilder class improve the performance in the background?
HWThanks!
HW>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Jul 31 '06 #5

P: n/a
Hi,

That is not true, StringBuilder is intended to be used in constructing the
string, usually by concatenation ( Append ).
String is a "special" class , its a very used data type that is inmutable,
this mean that it cannot be changed, once it's created any modification will
create a new instance (and possible discard the old one). Meaning that you
may get a lot of instances in certain cirscuntances, like in a loop:
string s;
foreach( DataRow dr in dataset.Tables[0].Rows)
s = d + dr["column1"].ToString();

in the above code each time d is appened a new instance is created with the
needed size, the old one is copied first, then the second string is copied ,
later it's assigned and the old instance is marked to GCed . If you sum the
space needed you will see that in some moment you are using twice the memory
needed, one half in the old instance, the other in the new instance. Hope
you understand what is happening.

ITOH with the code:
StringBuilder sb = new StringBuilder();
foreach( DataRow dr in dataset.Tables[0].Rows)
sb.Append(dr["column1"].ToString() );

there is no need to copy over the previous value, it just "add" the new
string. Now the next question is how this add is done, but it either
preallocate a buffer and when it's full reallocated a bigger buffer, or just
keep a concatenate list of buffers and when one is filled it just add
another.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Jul 31 '06 #6

P: n/a
Greg, a question...
When loop times is low, say

for(int i=0;i<8;i++) {
b+="hello";
}

should use the class StringBuilder? ... also

<HT />

"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:eg**************@TK2MSFTNGP05.phx.gbl...
In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because strings
are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs

StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();

each of the operations in the first loop create a new string as strings
are immutable (they cannot (well atleast in the safe world) be changed)...
the string builder continues using the same buffer. Since the string
builder uses the same object over and over (alterring an internal buffer)
it will use far less memory than the string example. The major speed gain
is realized in garbage collection and in the copying of memory ...

Creating objects in .NET is very fast, it is getting rid of them that is
slow .. since the first example creates so many intermediate objects the
garbage collector has alot of work to do to get rid of them.

For copying of memory the string example is basically copying the data for
the entire size of the string everytime a new string is created (for small
data sets this is rather minor but for big strings it gets quite
expensive). The StringBuilder class will also copy data if it has to
expand its buffer but will generally only have to copy the data that is
actually being appended (as opposed to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy


Jul 31 '06 #7

P: n/a
Harvey,

In this SPECIFIC case, no, since you know you have eight iterations of
the loop and you know the string you will be appending to the end result.

However, if you didn't know that "hello" was the string, and you didn't
know how many times through the loop you were iterating, then yes, a
StringBuilder would be best.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Harvey Triana" <ha**********@hotmail.comwrote in message
news:%2******************@TK2MSFTNGP03.phx.gbl...
Greg, a question...
When loop times is low, say

for(int i=0;i<8;i++) {
b+="hello";
}

should use the class StringBuilder? ... also

<HT />

"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:eg**************@TK2MSFTNGP05.phx.gbl...
>In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because strings
are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs

StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();

each of the operations in the first loop create a new string as strings
are immutable (they cannot (well atleast in the safe world) be
changed)... the string builder continues using the same buffer. Since the
string builder uses the same object over and over (alterring an internal
buffer) it will use far less memory than the string example. The major
speed gain is realized in garbage collection and in the copying of memory
...

Creating objects in .NET is very fast, it is getting rid of them that is
slow .. since the first example creates so many intermediate objects the
garbage collector has alot of work to do to get rid of them.

For copying of memory the string example is basically copying the data
for the entire size of the string everytime a new string is created (for
small data sets this is rather minor but for big strings it gets quite
expensive). The StringBuilder class will also copy data if it has to
expand its buffer but will generally only have to copy the data that is
actually being appended (as opposed to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>>Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy



Jul 31 '06 #8

P: n/a
Hi,

"Harvey Triana" <ha**********@hotmail.comwrote in message
news:%2******************@TK2MSFTNGP03.phx.gbl...
Greg, a question...
When loop times is low, say

for(int i=0;i<8;i++) {
b+="hello";
}

should use the class StringBuilder? ... also
Do you mean if you should use it when you only have just a few iterations?

It's debatable, if you look in the archives you will see several thread
about this. The results depend of the strings, the initial buffer and the
number of iterations.

IMO you should always use StringBuilder in a loop.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Jul 31 '06 #9

P: n/a
Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String concantinating.
The difference is start visible from concantinating about 25,000 strings
up to this number of thousand strings the significance is unsignificant (everything
depends on you environment)

HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HT>
HT<HT />
HT>
HT"Greg Young" <dr*******************@hotmail.comescribió en el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because
strings are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs
StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();
each of the operations in the first loop create a new string as
strings are immutable (they cannot (well atleast in the safe world)
be changed)... the string builder continues using the same buffer.
Since the string builder uses the same object over and over
(alterring an internal buffer) it will use far less memory than the
string example. The major speed gain is realized in garbage
collection and in the copying of memory ...

Creating objects in .NET is very fast, it is getting rid of them that
is slow .. since the first example creates so many intermediate
objects the garbage collector has alot of work to do to get rid of
them.

For copying of memory the string example is basically copying the
data for the entire size of the string everytime a new string is
created (for small data sets this is rather minor but for big strings
it gets quite expensive). The StringBuilder class will also copy data
if it has to expand its buffer but will generally only have to copy
the data that is actually being appended (as opposed to all of the
data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>>Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the
background?
Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Jul 31 '06 #10

P: n/a
Hello Hardy,
HWHi all,
HWI know it is better to handle large string with a StringBuilder,
HWbut how
HWdoes StringBuilder class improve the performance in the background?
HWThanks!
HW>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Jul 31 '06 #11

P: n/a
I would like to see this sample showing the difference is insignificant
until 25000 strings as this is in fact not the case ...

public static void TenThousandWithString() {
string s = "";
for (int i = 0; i < 10000; i++) {
s += i.ToString();
}
DummyString = s;

}

public static void TenThousandWithStringBuilder() {
StringBuilder s = new StringBuilder(50000);
for (int i = 0; i < 10000; i++) {
s.Append(i.ToString());
}
DummyString = s.ToString();
}

for 1000 runs ...

Test : String took 190539874570.188 ns, average ns = 190539874.570188
Test : StringBuilder took 3698780828.64676 ns, average ns = 3698780.82864676

I would say that being 60 times faster is fairly noticable wouldn't you?

at 1000 concats its still 5 times faster... and these are small strings ...
with bigger strings the speed difference increases.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsoft .com...
Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000 strings
up to this number of thousand strings the significance is unsignificant
(everything depends on you environment)

HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>>In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because
strings are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs
StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();
each of the operations in the first loop create a new string as
strings are immutable (they cannot (well atleast in the safe world)
be changed)... the string builder continues using the same buffer.
Since the string builder uses the same object over and over
(alterring an internal buffer) it will use far less memory than the
string example. The major speed gain is realized in garbage
collection and in the copying of memory ...

Creating objects in .NET is very fast, it is getting rid of them that
is slow .. since the first example creates so many intermediate
objects the garbage collector has alot of work to do to get rid of
them.

For copying of memory the string example is basically copying the
data for the entire size of the string everytime a new string is
created (for small data sets this is rather minor but for big strings
it gets quite expensive). The StringBuilder class will also copy data
if it has to expand its buffer but will generally only have to copy
the data that is actually being appended (as opposed to all of the
data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl.. .

Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the
background?
Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche


Jul 31 '06 #12

P: n/a
There is a break even point when it is passed the string may actually be
slightly faster than the stringbuilder (these are generally very small
numbers like 6 (and when being compared to s tringbuilder without an initial
size as it has to grow its internal buffer which equates to almost exactly
what is happenning in the case of string)

Generally I tell people to stay away from this code unless they are _really_
optimizing an area as often times requirements will change slightly and the
stringbuilder will become faster.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Harvey Triana" <ha**********@hotmail.comwrote in message
news:%2******************@TK2MSFTNGP03.phx.gbl...
Greg, a question...
When loop times is low, say

for(int i=0;i<8;i++) {
b+="hello";
}

should use the class StringBuilder? ... also

<HT />

"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:eg**************@TK2MSFTNGP05.phx.gbl...
>In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because strings
are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs

StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();

each of the operations in the first loop create a new string as strings
are immutable (they cannot (well atleast in the safe world) be
changed)... the string builder continues using the same buffer. Since the
string builder uses the same object over and over (alterring an internal
buffer) it will use far less memory than the string example. The major
speed gain is realized in garbage collection and in the copying of memory
...

Creating objects in .NET is very fast, it is getting rid of them that is
slow .. since the first example creates so many intermediate objects the
garbage collector has alot of work to do to get rid of them.

For copying of memory the string example is basically copying the data
for the entire size of the string everytime a new string is created (for
small data sets this is rather minor but for big strings it gets quite
expensive). The StringBuilder class will also copy data if it has to
expand its buffer but will generally only have to copy the data that is
actually being appended (as opposed to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>>Hi all,
I know it is better to handle large string with a StringBuilder, but
how does StringBuilder class improve the performance in the background?

Thanks!

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy



Jul 31 '06 #13

P: n/a
Hello Greg,

There http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.

I'm not declaring that SB doesn't hinder the performance. It really hinders,
but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn hurts
us in one app, and use SB to concat 6 string where performance will be hurted
severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple of
secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GY>
GYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GY>
GYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GY>
GYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GY>
GYI would say that being 60 times faster is fairly noticable wouldn't
GYyou?
GY>
GYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GY>
GYCheers,
GY>
GYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.microso ft.com...
GY>
>Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>>>In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because
strings are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs
StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();
each of the operations in the first loop create a new string as
strings are immutable (they cannot (well atleast in the safe world)
be changed)... the string builder continues using the same buffer.
Since the string builder uses the same object over and over
(alterring an internal buffer) it will use far less memory than the
string example. The major speed gain is realized in garbage
collection and in the copying of memory ...
Creating objects in .NET is very fast, it is getting rid of them
that is slow .. since the first example creates so many
intermediate objects the garbage collector has alot of work to do
to get rid of them.

For copying of memory the string example is basically copying the
data for the entire size of the string everytime a new string is
created (for small data sets this is rather minor but for big
strings it gets quite expensive). The StringBuilder class will also
copy data if it has to expand its buffer but will generally only
have to copy the data that is actually being appended (as opposed
to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl. ..
Hi all,
I know it is better to handle large string with a StringBuilder,
but
how does StringBuilder class improve the performance in the
background?
Thanks!
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Jul 31 '06 #14

P: n/a
I guess you don't find it important until it takes a full second as opposed
to < 100 ms? This is already atleast 10 times faster and can make a HUGE
difference in the running time of your app as this is a CPU bound task (it
uses 100% CPU on a CPU while doing this which means if you do this alot your
CPU usage will needlessly go up).

Your code also only runs it once which completely ignores the GC penalty
incurred by the string methodology. Which my guess would make it closer to
15-20 times slower.
and use SB to concat 6 string where performance will be hurted severe.
The penalty for using a SB is NEVER severe if used properly (unless you are
concating say 2 strings) .. the penalty is only severe for using strings ...
that is why it is best to error on the side of caution and use a
stringbuilder.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsoft .com...
Hello Greg,

There
http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.
I'm not declaring that SB doesn't hinder the performance. It really
hinders, but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn hurts
us in one app, and use SB to concat 6 string where performance will be
hurted severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple of
secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GYGYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GYGYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GYGYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GYGYI would say that being 60 times faster is fairly noticable
wouldn't
GYyou?
GYGYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GYGYCheers,
GYGYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.microso ft.com...
GY>
>>Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
In the background? Not sure I am understanding you here.
>
The reason StringBuilder is generally more performant is because
strings are immutable.
>
string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs
StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();
each of the operations in the first loop create a new string as
strings are immutable (they cannot (well atleast in the safe world)
be changed)... the string builder continues using the same buffer.
Since the string builder uses the same object over and over
(alterring an internal buffer) it will use far less memory than the
string example. The major speed gain is realized in garbage
collection and in the copying of memory ...
Creating objects in .NET is very fast, it is getting rid of them
that is slow .. since the first example creates so many
intermediate objects the garbage collector has alot of work to do
to get rid of them.
>
For copying of memory the string example is basically copying the
data for the entire size of the string everytime a new string is
created (for small data sets this is rather minor but for big
strings it gets quite expensive). The StringBuilder class will also
copy data if it has to expand its buffer but will generally only
have to copy the data that is actually being appended (as opposed
to all of the data).
>
Cheers,
>
Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl.. .
>Hi all,
>I know it is better to handle large string with a StringBuilder,
>but
>how does StringBuilder class improve the performance in the
>background?
>Thanks!
>--
>WWW: http://hardywang.1accesshost.com
>ICQ: 3359839
>yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche


Jul 31 '06 #15

P: n/a
Oh thanks, this is a good discussion. Suggest another question:

When i write:
return IntegerPart + " " + MoneyName + " " & RealPart;

- how may strings are create before Return is a single string?

Should be use ScringBuilder in this case?

<HT />
"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:%2****************@TK2MSFTNGP03.phx.gbl...
>I guess you don't find it important until it takes a full second as opposed
to < 100 ms? This is already atleast 10 times faster and can make a HUGE
difference in the running time of your app as this is a CPU bound task (it
uses 100% CPU on a CPU while doing this which means if you do this alot
your CPU usage will needlessly go up).

Your code also only runs it once which completely ignores the GC penalty
incurred by the string methodology. Which my guess would make it closer to
15-20 times slower.
>and use SB to concat 6 string where performance will be hurted severe.

The penalty for using a SB is NEVER severe if used properly (unless you
are concating say 2 strings) .. the penalty is only severe for using
strings ... that is why it is best to error on the side of caution and use
a stringbuilder.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsoft .com...
>Hello Greg,

There
http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.
I'm not declaring that SB doesn't hinder the performance. It really
hinders, but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn
hurts us in one app, and use SB to concat 6 string where performance will
be hurted severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple
of secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GYGYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GYGYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GYGYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GYGYI would say that being 60 times faster is fairly noticable
wouldn't
GYyou?
GYGYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GYGYCheers,
GYGYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.micros oft.com...
GY>
>>>Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>In the background? Not sure I am understanding you here.
>>
>The reason StringBuilder is generally more performant is because
>strings are immutable.
>>
>string b = "";
>for(int i=0;i<100;i++) {
>b+="hello";
>}
>return b;
>vs
>StringBuilder b = new StringBuilder(InitialSize);
>for(int i=0;i<100;i++) {
>b.Append("hello");
>}
>return b.ToString();
>each of the operations in the first loop create a new string as
>strings are immutable (they cannot (well atleast in the safe world)
>be changed)... the string builder continues using the same buffer.
>Since the string builder uses the same object over and over
>(alterring an internal buffer) it will use far less memory than the
>string example. The major speed gain is realized in garbage
>collection and in the copying of memory ...
>Creating objects in .NET is very fast, it is getting rid of them
>that is slow .. since the first example creates so many
>intermediate objects the garbage collector has alot of work to do
>to get rid of them.
>>
>For copying of memory the string example is basically copying the
>data for the entire size of the string everytime a new string is
>created (for small data sets this is rather minor but for big
>strings it gets quite expensive). The StringBuilder class will also
>copy data if it has to expand its buffer but will generally only
>have to copy the data that is actually being appended (as opposed
>to all of the data).
>>
>Cheers,
>>
>Greg Young
>MVP - C#
>http://codebetter.com/blogs/gregyoung
>"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
>news:%2****************@TK2MSFTNGP05.phx.gbl. ..
>>Hi all,
>>I know it is better to handle large string with a StringBuilder,
>>but
>>how does StringBuilder class improve the performance in the
>>background?
>>Thanks!
>>--
>>WWW: http://hardywang.1accesshost.com
>>ICQ: 3359839
>>yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche



Jul 31 '06 #16

P: n/a
Michael Nemtsev <ne*****@msn.comwrote:
I've posted the sample about 2 month ago, comparing SB and String
concantinating. The difference is start visible from concantinating
about 25,000 strings up to this number of thousand strings the
significance is unsignificant (everything depends on you environment)
That depends on what you mean by "significant". The difference between
using StringBuilder and string becomes detectable over the course of
several iterations of the whole operation *much* earlier than that.
StringBuilder becomes orders of magnitude faster than string
concatenation at relatively small numbers of concatenations.

While it's true that the overall operation is still fast, if you're
doing enough concatenation (even in smallish batches) StringBuilder is
still much faster.

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

P: n/a
Harvey Triana <ha**********@hotmail.comwrote:
Oh thanks, this is a good discussion. Suggest another question:

When i write:
return IntegerPart + " " + MoneyName + " " & RealPart;

- how may strings are create before Return is a single string?
No more than would be created using StringBuilder, and no StringBuilder
instance is required.
Should be use ScringBuilder in this case?
Absolutely not.

See http://www.pobox.com/~skeet/csharp/stringbuilder.html

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

P: n/a
the answer here is (n -1) ... 4 ... since these strings are all short its
not too big of a deal (the copies are of say 8 bytes as opposed to 800 or
8000) :)

I think in a case like this you are fine to just use strings when it gets
much bigger is when you run into problems (i.e. if you see a loop you have a
problem:)).

If this is a place where micro-optimization is very important to you just
remember to measure measure measure .... and when you are done measure some
more.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Harvey Triana" <ha**********@hotmail.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
Oh thanks, this is a good discussion. Suggest another question:

When i write:
return IntegerPart + " " + MoneyName + " " & RealPart;

- how may strings are create before Return is a single string?

Should be use ScringBuilder in this case?

<HT />
"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:%2****************@TK2MSFTNGP03.phx.gbl...
>>I guess you don't find it important until it takes a full second as
opposed to < 100 ms? This is already atleast 10 times faster and can make
a HUGE difference in the running time of your app as this is a CPU bound
task (it uses 100% CPU on a CPU while doing this which means if you do
this alot your CPU usage will needlessly go up).

Your code also only runs it once which completely ignores the GC penalty
incurred by the string methodology. Which my guess would make it closer
to 15-20 times slower.
>>and use SB to concat 6 string where performance will be hurted severe.

The penalty for using a SB is NEVER severe if used properly (unless you
are concating say 2 strings) .. the penalty is only severe for using
strings ... that is why it is best to error on the side of caution and
use a stringbuilder.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsof t.com...
>>Hello Greg,

There
http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.
I'm not declaring that SB doesn't hinder the performance. It really
hinders, but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn
hurts us in one app, and use SB to concat 6 string where performance
will be hurted severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple
of secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GYGYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GYGYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GYGYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GYGYI would say that being 60 times faster is fairly noticable
wouldn't
GYyou?
GYGYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GYGYCheers,
GYGYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.micro soft.com...
GY>
Hello Harvey,
>
I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>>In the background? Not sure I am understanding you here.
>>>
>>The reason StringBuilder is generally more performant is because
>>strings are immutable.
>>>
>>string b = "";
>>for(int i=0;i<100;i++) {
>>b+="hello";
>>}
>>return b;
>>vs
>>StringBuilder b = new StringBuilder(InitialSize);
>>for(int i=0;i<100;i++) {
>>b.Append("hello");
>>}
>>return b.ToString();
>>each of the operations in the first loop create a new string as
>>strings are immutable (they cannot (well atleast in the safe world)
>>be changed)... the string builder continues using the same buffer.
>>Since the string builder uses the same object over and over
>>(alterring an internal buffer) it will use far less memory than the
>>string example. The major speed gain is realized in garbage
>>collection and in the copying of memory ...
>>Creating objects in .NET is very fast, it is getting rid of them
>>that is slow .. since the first example creates so many
>>intermediate objects the garbage collector has alot of work to do
>>to get rid of them.
>>>
>>For copying of memory the string example is basically copying the
>>data for the entire size of the string everytime a new string is
>>created (for small data sets this is rather minor but for big
>>strings it gets quite expensive). The StringBuilder class will also
>>copy data if it has to expand its buffer but will generally only
>>have to copy the data that is actually being appended (as opposed
>>to all of the data).
>>>
>>Cheers,
>>>
>>Greg Young
>>MVP - C#
>>http://codebetter.com/blogs/gregyoung
>>"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
>>news:%2****************@TK2MSFTNGP05.phx.gbl ...
>>>Hi all,
>>>I know it is better to handle large string with a StringBuilder,
>>>but
>>>how does StringBuilder class improve the performance in the
>>>background?
>>>Thanks!
>>>--
>>>WWW: http://hardywang.1accesshost.com
>>>ICQ: 3359839
>>>yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche




Jul 31 '06 #19

P: n/a
Jon,

Just to be formal ...

There may be more objects created than with the stringbuilder it really
depends on what the variables come out as and the initial size of the
stringbuilder object (although I agree with you that the stringbuilder in
bad code here).

Cheers,

Greg

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP***********************@msnews.microsoft.co m...
Harvey Triana <ha**********@hotmail.comwrote:
>Oh thanks, this is a good discussion. Suggest another question:

When i write:
return IntegerPart + " " + MoneyName + " " & RealPart;

- how may strings are create before Return is a single string?

No more than would be created using StringBuilder, and no StringBuilder
instance is required.
>Should be use ScringBuilder in this case?

Absolutely not.

See http://www.pobox.com/~skeet/csharp/stringbuilder.html

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

Jul 31 '06 #20

P: n/a
Thanks to all.

<HT>

"Harvey Triana" <ha**********@hotmail.comescribió en el mensaje
news:%2****************@TK2MSFTNGP03.phx.gbl...
Oh thanks, this is a good discussion. Suggest another question:

When i write:
return IntegerPart + " " + MoneyName + " " & RealPart;

- how may strings are create before Return is a single string?

Should be use ScringBuilder in this case?

<HT />
"Greg Young" <dr*******************@hotmail.comescribió en el mensaje
news:%2****************@TK2MSFTNGP03.phx.gbl...
>>I guess you don't find it important until it takes a full second as
opposed to < 100 ms? This is already atleast 10 times faster and can make
a HUGE difference in the running time of your app as this is a CPU bound
task (it uses 100% CPU on a CPU while doing this which means if you do
this alot your CPU usage will needlessly go up).

Your code also only runs it once which completely ignores the GC penalty
incurred by the string methodology. Which my guess would make it closer
to 15-20 times slower.
>>and use SB to concat 6 string where performance will be hurted severe.

The penalty for using a SB is NEVER severe if used properly (unless you
are concating say 2 strings) .. the penalty is only severe for using
strings ... that is why it is best to error on the side of caution and
use a stringbuilder.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsof t.com...
>>Hello Greg,

There
http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.
I'm not declaring that SB doesn't hinder the performance. It really
hinders, but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn
hurts us in one app, and use SB to concat 6 string where performance
will be hurted severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple
of secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GYGYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GYGYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GYGYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GYGYI would say that being 60 times faster is fairly noticable
wouldn't
GYyou?
GYGYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GYGYCheers,
GYGYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.micro soft.com...
GY>
Hello Harvey,
>
I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
>>In the background? Not sure I am understanding you here.
>>>
>>The reason StringBuilder is generally more performant is because
>>strings are immutable.
>>>
>>string b = "";
>>for(int i=0;i<100;i++) {
>>b+="hello";
>>}
>>return b;
>>vs
>>StringBuilder b = new StringBuilder(InitialSize);
>>for(int i=0;i<100;i++) {
>>b.Append("hello");
>>}
>>return b.ToString();
>>each of the operations in the first loop create a new string as
>>strings are immutable (they cannot (well atleast in the safe world)
>>be changed)... the string builder continues using the same buffer.
>>Since the string builder uses the same object over and over
>>(alterring an internal buffer) it will use far less memory than the
>>string example. The major speed gain is realized in garbage
>>collection and in the copying of memory ...
>>Creating objects in .NET is very fast, it is getting rid of them
>>that is slow .. since the first example creates so many
>>intermediate objects the garbage collector has alot of work to do
>>to get rid of them.
>>>
>>For copying of memory the string example is basically copying the
>>data for the entire size of the string everytime a new string is
>>created (for small data sets this is rather minor but for big
>>strings it gets quite expensive). The StringBuilder class will also
>>copy data if it has to expand its buffer but will generally only
>>have to copy the data that is actually being appended (as opposed
>>to all of the data).
>>>
>>Cheers,
>>>
>>Greg Young
>>MVP - C#
>>http://codebetter.com/blogs/gregyoung
>>"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
>>news:%2****************@TK2MSFTNGP05.phx.gbl ...
>>>Hi all,
>>>I know it is better to handle large string with a StringBuilder,
>>>but
>>>how does StringBuilder class improve the performance in the
>>>background?
>>>Thanks!
>>>--
>>>WWW: http://hardywang.1accesshost.com
>>>ICQ: 3359839
>>>yours Hardy
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour
"At times one remains faithful to a cause only because its opponents
do not cease to be insipid." (c) Friedrich Nietzsche
>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche




Jul 31 '06 #21

P: n/a
Greg Young <dr*******************@hotmail.comwrote:
Just to be formal ...

There may be more objects created than with the stringbuilder it really
depends on what the variables come out as and the initial size of the
stringbuilder object (although I agree with you that the stringbuilder in
bad code here).
Well, String.Concat (which is used internally) would deal with the 5
input strings, and then come out with one output string.

Is your point that StringBuilder might not need to convert IntegerPart,
MoneyPart and RealPart into strings first? I hadn't thought of that...

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

P: n/a
Greg Young <dr*******************@hotmail.comwrote:
the answer here is (n -1) ... 4 ... since these strings are all short its
not too big of a deal (the copies are of say 8 bytes as opposed to 800 or
8000) :)
No extra strings are created for the concatenation. IntegerPart,
MoneyName and RealPart are converted into strings, but it *doesn't*
calculate (IntegerPart + " "), then add MoneyName to that, then add
" " to that, then RealPart.

Instead, it calls String.Concat. Unfortunately in this case it needs to
use String.Concat(String[]) as there are only overloads for
String.Concat as far as four strings. It doesn't build up any temporary
strings though, beyond the strings to concatenate in the first place.

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

P: n/a
Yes Jon although in the current implementation does create those strings ...

public StringBuilder Append(int value)
{
return this.Append(value.ToString(CultureInfo.CurrentCult ure));
}

Theoretically the implementation could create the string versions directly
in its buffer.

Cheers,

Greg
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Greg Young <dr*******************@hotmail.comwrote:
>Just to be formal ...

There may be more objects created than with the stringbuilder it really
depends on what the variables come out as and the initial size of the
stringbuilder object (although I agree with you that the stringbuilder in
bad code here).

Well, String.Concat (which is used internally) would deal with the 5
input strings, and then come out with one output string.

Is your point that StringBuilder might not need to convert IntegerPart,
MoneyPart and RealPart into strings first? I hadn't thought of that...

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

Jul 31 '06 #24

P: n/a
I guess you don't find it important until it takes a full second as opposed
to < 100 ms?
and until the response time is important (performance).
I see no reason to stick SB wherever it possible. On the back-end - indeed,
but on client - arguably, till we have no the reason for this(like number of
string in cycle)
>This is already atleast 10 times faster and can make a HUGE
difference in the running time of your app as this is a CPU bound task (it
uses 100% CPU on a CPU while doing this which means if you do this alot your
CPU usage will needlessly go up).
Sure, but it depends on type of app, whether it concerns us or not
Your code also only runs it once which completely ignores the GC penalty
incurred by the string methodology. Which my guess would make it closer to
15-20 times slower.
yes, but we haven't discuss how much it should be run :) we just concatenate
strings :)
If we need to run in several times Strings are not appropriate
and use SB to concat 6 string where performance will be hurted severe.
The penalty for using a SB is NEVER severe if used properly (unless you are
concating say 2 strings) .. the penalty is only severe for using strings ...
that is why it is best to error on the side of caution and use a
stringbuilder.
There I was talking about strings :) mistyped.

I'm not arguing that Strings are good and "use String wherever it possible"
I want to say that the String isn't the evil as we discuss there :), but it
could be the evil if we dont understand how and where to use Strings or SB.
We need to see the app where OP use it, how and when.
What to say if we are struggling to save 1-2 seconds and then below in code
we could see the huge XSLT transformation that isn't optimized and takes 30
secs. Those saved 1-2 sec doesn't make any sense in this context :)

I've been reviewing code periodically, and have seen a lot of times that
people sticks SB even to concanting 2-3 strings, where you can use strings.
And this hasty using SB (because smbd have read somewhere that is very quick)
really influence on code readability. We are most read code rather then write
it.

Optimizing is for that have to be optimizing :)
Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung

"Michael Nemtsev" <ne*****@msn.comwrote in message
news:9c**************************@msnews.microsoft .com...
Hello Greg,

There
http://groups.google.com/group/micro...8fc6a2b950ddad

but a bit bigger number of string.
I'm not declaring that SB doesn't hinder the performance. It really
hinders, but we need to understand where this hindering is important.
We can concantinate 10,000 string with SB for 0.09sec and this doesn hurts
us in one app, and use SB to concat 6 string where performance will be
hurted severe.
Everything depends on your context
I'm for the simplicity if we are not struggle for the additional couple of
secs

GYI would like to see this sample showing the difference is
GYinsignificant until 25000 strings as this is in fact not the case
GY...
GYGYpublic static void TenThousandWithString() {
GYstring s = "";
GYfor (int i = 0; i < 10000; i++) {
GYs += i.ToString();
GY}
GYDummyString = s;
GY}
GYGYpublic static void TenThousandWithStringBuilder() {
GYStringBuilder s = new StringBuilder(50000);
GYfor (int i = 0; i < 10000; i++) {
GYs.Append(i.ToString());
GY}
GYDummyString = s.ToString();
GY}
GYfor 1000 runs ...
GYGYTest : String took 190539874570.188 ns, average ns =
GY190539874.570188 Test : StringBuilder took 3698780828.64676 ns,
GYaverage ns = 3698780.82864676
GYGYI would say that being 60 times faster is fairly noticable
wouldn't
GYyou?
GYGYat 1000 concats its still 5 times faster... and these are small
GYstrings ... with bigger strings the speed difference increases.
GYGYCheers,
GYGYGreg Young
GYMVP - C#
GYhttp://codebetter.com/blogs/gregyoung
GY"Michael Nemtsev" <ne*****@msn.comwrote in message
GYnews:9c**************************@msnews.microso ft.com...
GY>
>Hello Harvey,

I've posted the sample about 2 month ago, comparing SB and String
concantinating.
The difference is start visible from concantinating about 25,000
strings
up to this number of thousand strings the significance is
unsignificant
(everything depends on you environment)
HTGreg, a question...
HTWhen loop times is low, say
HTfor(int i=0;i<8;i++) {
HTb+="hello";
HT}
HTshould use the class StringBuilder? ... also
HTHT<HT />
HTHT"Greg Young" <dr*******************@hotmail.comescribió en
el
HTmensaje news:eg**************@TK2MSFTNGP05.phx.gbl...
HT>
In the background? Not sure I am understanding you here.

The reason StringBuilder is generally more performant is because
strings are immutable.

string b = "";
for(int i=0;i<100;i++) {
b+="hello";
}
return b;
vs
StringBuilder b = new StringBuilder(InitialSize);
for(int i=0;i<100;i++) {
b.Append("hello");
}
return b.ToString();
each of the operations in the first loop create a new string as
strings are immutable (they cannot (well atleast in the safe world)
be changed)... the string builder continues using the same buffer.
Since the string builder uses the same object over and over
(alterring an internal buffer) it will use far less memory than the
string example. The major speed gain is realized in garbage
collection and in the copying of memory ...
Creating objects in .NET is very fast, it is getting rid of them
that is slow .. since the first example creates so many
intermediate objects the garbage collector has alot of work to do
to get rid of them.

For copying of memory the string example is basically copying the
data for the entire size of the string everytime a new string is
created (for small data sets this is rather minor but for big
strings it gets quite expensive). The StringBuilder class will also
copy data if it has to expand its buffer but will generally only
have to copy the data that is actually being appended (as opposed
to all of the data).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
"Hardy Wang" <ha*******@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl. ..
Hi all,
I know it is better to handle large string with a StringBuilder,
but
how does StringBuilder class improve the performance in the
background?
Thanks!
--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche

Aug 1 '06 #25

P: n/a
Michael Nemtsev wrote:
I guess you don't find it important until it takes a full second as opposed
to < 100 ms?

and until the response time is important (performance).
I see no reason to stick SB wherever it possible. On the back-end - indeed,
but on client - arguably, till we have no the reason for this(like number of
string in cycle)
That's very different from claiming there's no visible difference until
you concatenate about 25,000 strings though. Having a known but
acceptable performance hit is one thing - claiming the hit isn't there
is another.

Yes, the times taken are both small - in the same way that both an atom
and a speck of dust are small. There's still a vast difference between
them in size though - and it's misleading to imply that there isn't, as
your post did IMO.

Jon

Aug 1 '06 #26

P: n/a
Hello Jon Skeet [C# MVP],

JMichael Nemtsev wrote:
J>
>>I guess you don't find it important until it takes a full second as
opposed to < 100 ms?
and until the response time is important (performance).
I see no reason to stick SB wherever it possible. On the back-end -
indeed,
but on client - arguably, till we have no the reason for this(like
number of
string in cycle)
JThat's very different from claiming there's no visible difference
Juntil you concatenate about 25,000 strings though. Having a known but
Jacceptable performance hit is one thing - claiming the hit isn't
Jthere is another.

Jon I didn't claim that hit absolutely isn't here. I pointed that "it depends
on your environment", and in the last post I've expained what I meant.

JYes, the times taken are both small - in the same way that both an
Jatom and a speck of dust are small. There's still a vast difference
Jbetween them in size though - and it's misleading to imply that there
Jisn't, as your post did IMO.

Probably, I wasn't clear to point my idea

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Aug 1 '06 #27

This discussion thread is closed

Replies have been disabled for this discussion.