473,386 Members | 1,668 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,386 software developers and data experts.

stringbuilder performance questions

Hi,

It is generally stated that stringbuilder should be used instead of
just concatenating strings with the plus operator.

That's fine enough what I'm wondering in cases I have:

String S = "hello" + World;

Does it make any sense to use Stringbuilder in a case like the above,
where the concatenation only takes place in the declaration of the
variable, as opposed to :

String S = "";

S = "hello" + World;
S = S + " from me";
where I can see the obvious benefits.

Aside from concatenation does StringBuilder provide performance
benefits if I am overwriting the value of the String at different
places, for example during a loop? I suppose the answer there would be
yes because the size of the string is thus dynamically set in each
iteration, but is StringBuilder the correct solution for this or
should I use some other tool.

Jan 28 '08 #1
5 4337
On Jan 28, 12:05 pm, pantagruel <rasmussen.br...@gmail.comwrote:
It is generally stated that stringbuilder should be used instead of
just concatenating strings with the plus operator.
Well, it entirely depends on the situation.
That's fine enough what I'm wondering in cases I have:

String S = "hello" + World;

Does it make any sense to use Stringbuilder in a case like the above,
where the concatenation only takes place in the declaration of the
variable, as opposed to :

String S = "";

S = "hello" + World;
S = S + " from me";
where I can see the obvious benefits.
In fact, with just a couple of concatenations you'd probably still not
get a performance benefit from using StringBuilder. As ever with
performance issues, "it depends".
Aside from concatenation does StringBuilder provide performance
benefits if I am overwriting the value of the String at different
places, for example during a loop? I suppose the answer there would be
yes because the size of the string is thus dynamically set in each
iteration, but is StringBuilder the correct solution for this or
should I use some other tool.
If you don't need intermediate values and you're looping round a
reasonable number of times (or an unknown number) then StringBuilder
is the way to go.

See http://pobox.com/~skeet/csharp/stringbuilder.html for more
information.

Jon
Jan 28 '08 #2
Hi,
This has been discussed ad nauseam, if you check the archives you will see
that in cases like the one you describe there is no diffeence.
The real difference is when you use it in a loop.

But again, look into the archives.

--
Ignacio Machin
http://www.laceupsolutions.com
Mobile & warehouse Solutions.
"pantagruel" <ra*************@gmail.comwrote in message
news:e7**********************************@s19g2000 prg.googlegroups.com...
Hi,

It is generally stated that stringbuilder should be used instead of
just concatenating strings with the plus operator.

That's fine enough what I'm wondering in cases I have:

String S = "hello" + World;

Does it make any sense to use Stringbuilder in a case like the above,
where the concatenation only takes place in the declaration of the
variable, as opposed to :

String S = "";

S = "hello" + World;
S = S + " from me";
where I can see the obvious benefits.

Aside from concatenation does StringBuilder provide performance
benefits if I am overwriting the value of the String at different
places, for example during a loop? I suppose the answer there would be
yes because the size of the string is thus dynamically set in each
iteration, but is StringBuilder the correct solution for this or
should I use some other tool.

Jan 28 '08 #3

Concatenation within a single line is better done with the + operator
instead of with StringBuilder. StringBuilder is best when
concatenating across lines, especially in loops and such. Especially
if you're overwriting portions of the text, then StringBuilder is
best.

Other things to keep in mind is pre-initialize a good size for your
StringBuilder if you're building lots of strings, especially if
they're similar in size. It's better to have originally built a
StringBuilder that had too high of a capacity than to have to expand
it several times, ex

StringBuilder builder = new StringBuilder(64);

if you're expecting to make strings between 32 and 64 chars.

Another thing to keep in mind is that String.Join() has even better
performance than StringBuilder so if you're essentially joining
together a bunch of lines, consider using that (but don't contort your
situation into using String.Join unnecessarily).

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

On Mon, 28 Jan 2008 04:05:34 -0800 (PST), pantagruel
<ra*************@gmail.comwrote:
>Hi,

It is generally stated that stringbuilder should be used instead of
just concatenating strings with the plus operator.

That's fine enough what I'm wondering in cases I have:

String S = "hello" + World;

Does it make any sense to use Stringbuilder in a case like the above,
where the concatenation only takes place in the declaration of the
variable, as opposed to :

String S = "";

S = "hello" + World;
S = S + " from me";
where I can see the obvious benefits.

Aside from concatenation does StringBuilder provide performance
benefits if I am overwriting the value of the String at different
places, for example during a loop? I suppose the answer there would be
yes because the size of the string is thus dynamically set in each
iteration, but is StringBuilder the correct solution for this or
should I use some other tool.
Jan 28 '08 #4
On Wed, 30 Jan 2008 05:59:52 -0800, Samuel R. Neff <sa********@nomail.com>
wrote:
There is no reason to ignore well-known performance tips just because
the net effect is small in many cases. It's always good to which
techniques perform better than others and do things the right way in
the first place.

I'm really amazed you're arguing against using StringBuilder or
teaching someone best practices.
I don't think he is. I think he's arguing that there are other concerns
than just performance. In many situations, using a string with
concatenation may be more readable or maintainable than using a
StringBuilder, and if those are situations in which it's known that the
concatenation will never be a noticable performance problem, then it makes
sense to use concatenation instead.

He's also quite right in pointing out that if you think you need to
pre-initialize the StringBuilder with some fixed constant, that "64" is
way too small to be useful (unless, of course, you have reason to believe
that your strings will _never_ exceed 64 characters).

Now, I think he may be overstating the relative likelihoods of the
comparative scenarios. Some applications may spend a lot of time building
new strings from numerous small pieces. While the majority of
applications may not have this characteristic, that doesn't mean that
there aren't a good number of correct implementations that would require
that behavior. So if anything, I would disagree with the statement that
"things are very wrong" if an application needs to use StringBuilder.

Just knowing that an application is bounded by its string concatenation
behavior doesn't tell you anything about whether that application is
"wrong" or "right".

If anything, he's simply guilty of making broad, unfounded
generalizations. But otherwise, the basic gist of his advice is sound:
just because StringBuilder performs better in the unbounded case, that
doesn't mean that it's actually the right thing to use all of the time.

Pete
Jan 30 '08 #5
On Wed, 30 Jan 2008 05:59:52 -0800, Samuel R. Neff
<sa********@nomail.comwrote:
>There is no reason to ignore well-known performance tips just because
the net effect is small in many cases.
The use of StringBuilder decreases performance over naive concat in a
large number of cases I have seen it used.

Far too often, I've seen:

StringBuilder sb = new StringBuilder();
sb.Append("Foo ");
sb.Append(myVar.ToString());
sb.Append(" bar ");
sb.Append(someMethod());
etc(sb);
return sb.ToString();

Eugh! *Far* slower than a concat, and far less clear.
>It's always good to which
techniques perform better than others and do things the right way in
the first place.
In some languages, performance is often really important. Javascript is
a good example; it's an interpreted language and you're trying to do
interesting real-time stuff on somebody's 100MHz PC.

In Javascript, it's quite common to see loops like this:

for(var i = 0, l = myArray.length; i < l; i++)
{
doSomething();
}

It's faster - you don't have to get myArray.length more times than you
need to.

I strongly suspect this would also be faster in C# (the JIT compiler
might optimize it to the same code for arrays if it's good, but it
couldn't do Lists).
It's not a good idea - performance is rarely an issue in C#.

Generally, I think it's best to optimize for maintainability. The
majority of programs spend >95% of their CPU time in a few methods - you
only need to optimize for speed in those methods, if at all.
>I'm really amazed you're arguing against using StringBuilder or
teaching someone best practices.
Peter Duniho wrote:
I don't think he is. I think he's arguing that there are other concerns
than just performance. In many situations, using a string with
concatenation may be more readable or maintainable than using a
StringBuilder, and if those are situations in which it's known that the
concatenation will never be a noticable performance problem, then it
makes sense to use concatenation instead.

He's also quite right in pointing out that if you think you need to
pre-initialize the StringBuilder with some fixed constant, that "64" is
way too small to be useful (unless, of course, you have reason to
believe that your strings will _never_ exceed 64 characters).

Now, I think he may be overstating the relative likelihoods of the
comparative scenarios. Some applications may spend a lot of time
building new strings from numerous small pieces. While the majority of
applications may not have this characteristic, that doesn't mean that
there aren't a good number of correct implementations that would require
that behavior.
StringBuilders get abused both as a 'fast' concat, and a pseudo-stream.

Simple programs that manipulate strings should generally work on
streams. More complex programs should generally parse the string into a
more sensible internal structure and work on that instead.

Nice UNICODE strings are lovely for humans, but about the worst possible
choice of internal data type.

It doesn't help that people who havn't quite figured this out yet get
told "it's okay - just use a StringBuilder instead"
So if anything, I would disagree with the statement that
"things are very wrong" if an application needs to use StringBuilder.
Sometimes, you have to maintain code that should have got the author
many years in jail. Perhaps it's doing some complicated mathematics by
constructing an huge SQL query to send to a database server and getting
the result back as a scalar. (Yes, people really do write code like this)

If it needs to be more performant, you might profile it and find that
it's bound by the speed it can concat strings together in a particular
method. If it doesn't make economic sense to do a total rewrite, a quick
and dirty solution would be to change that method to use a StringBuilder.

There are few good reasons to use a StringBuilder outside of this
scenario (although I will admit they do exist - as do good reasons to
use TypedReferences, try{}IL-fault{} blocks, VB.NET, etc).

Alun Harford
Jan 30 '08 #6

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...
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
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...
26
by: Hardy Wang | last post by:
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:...
3
by: Morgan Cheng | last post by:
In P/Invoke situation, If some *out* parameter is LPWSTR, I can use string or StringBuilder. However, there is one problem about StringBuilder. By default, its Capacity is 16. If the returned...
9
by: Michael D. Ober | last post by:
OK, I can't figure out a way to optimize the following VB 2005 code using StringBuilders: Public Const RecSize as Integer = 105 Private buffer As String Public Sub New() init End Sub...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...

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.