473,411 Members | 1,980 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

String and StringBuilder

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
26 3145
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
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,...
14
by: Bob | last post by:
I have a function that takes in a list of IDs (hundreds) as input parameter and needs to pass the data to another step as a comma delimited string. The source can easily create this list of IDs in...
5
by: Dave | last post by:
I'm receiving info from a com port into a string. I gradually process the string which constantly shortens it. The question is how long can a string be before I need to write some info to disk...
12
by: Tee | last post by:
String Builder & String, what's the difference. and when to use which ? Thanks.
9
by: Peter Row | last post by:
Hi, I know this has been asked before, but reading the threads it is still not entirely clear. Deciding which .Replace( ) to use when. Typically if I create a string in a loop I always use a...
12
by: Richard Lewis Haggard | last post by:
I thought that the whole point of StringBuilder was that it was supposed to be a faster way of building strings than string. However, I just put together a simple little application to do a...
10
by: Mo | last post by:
Hi, I am trying to write a code to build a string 768 characters long. This string is going to be written to a file which is then read by another application. The format of the string is already...
15
by: morleyc | last post by:
Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris
34
by: raylopez99 | last post by:
StringBuilder better and faster than string for adding many strings. Look at the below. It's amazing how much faster StringBuilder is than string. The last loop below is telling: for adding...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...

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.