473,761 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about the string Class and the StringBuilder class

Hello!

I read in a book and here is a question and the answer that I'm not
satisfied with.
When should you use the StringBuilder class instead of the String class.
1.When building a string from shorter strings.
2.When working with text data longer than 256 bytes.
3.When you want to search and replace the contents of a string
4.When a string is a value type.

The answer that I would choose would be 3 because string object is immutable
so
here is it an advantage to use the StringBuilder class but
according to the book is the right answer 1.

But if you build a string from shorter strings you don't have to use a
StringBuilder class as
string s = "This" + "is" + "a" + "Test";

I can accept numer 1 if they mean this.
string s;
s += "This";
s += "is";
s += "a";
s += "Test";

But it is somewhat unclear what they mean when they say building a string
from shorter strings.

Can somebody give a comment how the book can say that the right answer is
number 1

//Tony
Sep 22 '08 #1
13 2679
On Sep 22, 12:25*pm, "Tony Johansson" <johansson.ande rs...@telia.com >
wrote:
Hello!

I read in a book and here is a question and the answer that I'm not
satisfied with.
When should you use the StringBuilder class instead of the String class.
1.When building a string from shorter strings.
2.When working with text data longer than 256 bytes.
3.When you want to search and replace the contents of a string
4.When a string is a value type.

The answer that I would choose would be 3 because string object is immutable
so
here is it an advantage to use the StringBuilder class but
according to the book is the right answer 1.

But if you build a string from shorter strings you don't have to use a
StringBuilder class as
string s = "This" + "is" + "a" + "Test";

I can accept numer 1 if they mean this.
string s;
s += "This";
s += "is";
s += "a";
s += "Test";

But it is somewhat unclear what they mean when they say building a string
from shorter strings.

Can somebody give a comment how the book can say that the right answer is
number 1

//Tony
The book must have been referring to concatentation. StringBuilder
will be more efficient in that scenario because it uses techniques
that require fewer copy operations. See http://pobox.com/~skeet/csharp/stringbuilder.html
for more information.
Sep 22 '08 #2
On Sep 22, 1:13*pm, Brian Gideon <briangid...@ya hoo.comwrote:
On Sep 22, 12:25*pm, "Tony Johansson" <johansson.ande rs...@telia.com >
wrote:


Hello!
I read in a book and here is a question and the answer that I'm not
satisfied with.
When should you use the StringBuilder class instead of the String class..
1.When building a string from shorter strings.
2.When working with text data longer than 256 bytes.
3.When you want to search and replace the contents of a string
4.When a string is a value type.
The answer that I would choose would be 3 because string object is immutable
so
here is it an advantage to use the StringBuilder class but
according to the book is the right answer 1.
But if you build a string from shorter strings you don't have to use a
StringBuilder class as
string s = "This" + "is" + "a" + "Test";
I can accept numer 1 if they mean this.
string s;
s += "This";
s += "is";
s += "a";
s += "Test";
But it is somewhat unclear what they mean when they say building a string
from shorter strings.
Can somebody give a comment how the book can say that the right answer is
number 1
//Tony

The book must have been referring to concatentation. *StringBuilder
will be more efficient in that scenario because it uses techniques
that require fewer copy operations. *Seehttp://pobox.com/~skeet/csharp/stringbuilder.h tml
for more information.
Oh, by the way, I should point out that you're example is unique in
that the concatenation will occur at compile time since the individual
strings are constant. In that respect the StringBuilder would not
perform any better.
Sep 22 '08 #3
On Sep 22, 1:25 pm, "Tony Johansson" <johansson.ande rs...@telia.com >
wrote:
Hello!

I read in a book and here is a question and the answer that I'm not
satisfied with.
When should you use the StringBuilder class instead of the String class.
1.When building a string from shorter strings.
2.When working with text data longer than 256 bytes.
3.When you want to search and replace the contents of a string
4.When a string is a value type.

The answer that I would choose would be 3 because string object is immutable
so
here is it an advantage to use the StringBuilder class but
according to the book is the right answer 1.

But if you build a string from shorter strings you don't have to use a
StringBuilder class as
string s = "This" + "is" + "a" + "Test";

I can accept numer 1 if they mean this.
string s;
s += "This";
s += "is";
s += "a";
s += "Test";

But it is somewhat unclear what they mean when they say building a string
from shorter strings.

Can somebody give a comment how the book can say that the right answer is
number 1
The best answer is the 1.
I think that you will understand better why not is 3.
For example. if you want to replace the string "a" for "A" all you
have to do is call string.Replace (which assure you it will use the
most appropriated algorithm).

The example you provide of contatenation is not the best one. The
compiler will contatenate all the strings in only one @ compile time.
But the idea remains that each concatenation will generate one string.
so you end with a lot of temporaries strnigs that have no use. That
why is better to use StrngBuilder

Sep 22 '08 #4
Hi,

Let say I put them into boxes (memory block) to illustrate the activities
involved.

Example 1:

string s = "This" + "is" + "a" + "Test";

| s | |
| s | "This" |
| s | "This" | "is" |
| s | "This" | "is" | "a" |
| s | "This" | "is" | "a" | "Test" |

Example 2:

string s;
s += "This";
s += "is";
s += "a";
s += "Test";

| s | |
| s | "This" |
| s | "This" | "is" |
| s | "This" | "is" | "a" |
| s | "This" | "is" | "a" | "Test" |

Example 3:

StringBuilder s = new StringBuilder() ;
s.Append("This" );
s.Append("is");
s.Append("a");
s.Append("Test" );

| s | |
| s | "This" |
| s | "is" |
| s | "a" |
| s | "Test" |

* NOTE 1: Allocating new memory block is a very excessive activity.

* NOTE 2: Also consider that the reserved memory block only released during
the destructor/garbage collector decided to clear it off.

"Tony Johansson" <jo************ *****@telia.com wrote in message
news:Zx******** ********@newsb. telia.net...
Hello!

I read in a book and here is a question and the answer that I'm not
satisfied with.
When should you use the StringBuilder class instead of the String class.
1.When building a string from shorter strings.
2.When working with text data longer than 256 bytes.
3.When you want to search and replace the contents of a string
4.When a string is a value type.

The answer that I would choose would be 3 because string object is
immutable so
here is it an advantage to use the StringBuilder class but
according to the book is the right answer 1.

But if you build a string from shorter strings you don't have to use a
StringBuilder class as
string s = "This" + "is" + "a" + "Test";

I can accept numer 1 if they mean this.
string s;
s += "This";
s += "is";
s += "a";
s += "Test";

But it is somewhat unclear what they mean when they say building a string
from shorter strings.

Can somebody give a comment how the book can say that the right answer is
number 1

//Tony
Sep 22 '08 #5
OD
The best is to write a little test project. Test each solution in a big
loop and display time and CLR memory before and after. You'll be
surprised.

The academic solution is of course "use a stringbuilder".
But the reality is a bit different.. Strings are allocated in
generation 0, so mostly in the cpu cache. Short time living strings are
then allocated very quickly and are destroyed very quickly too.
A stringbuilder is a long life object compare to multiple little short
living strings, and when its buffer is full it reallocates it with a
bigger size.
As the objet is living a bit longer it can be pushed in generation 1
where it will be destroyed later than in generation 0 (as short living
strings)...

So, if it is very simple to find good samples that show where
StringBuilder is, with no doubt, the best solution, there are plenty of
real situations where the StringBuilder will not be the best solution.
concatenation of short living strings is often better (more often lot
of people is thinking).

Extreme cases are easy to understand, but extreme cases are also less
common in daily development... So don't be too much fool by the
"stringbuil der effiency myth".

--
OD___
www.e-naxos.com
Sep 24 '08 #6
OD <OD <webmaster @ e-naxos dot com>wrote:
The best is to write a little test project. Test each solution in a big
loop and display time and CLR memory before and after. You'll be
surprised.

The academic solution is of course "use a stringbuilder".
But the reality is a bit different.. Strings are allocated in
generation 0, so mostly in the cpu cache. Short time living strings are
then allocated very quickly and are destroyed very quickly too.
A stringbuilder is a long life object compare to multiple little short
living strings, and when its buffer is full it reallocates it with a
bigger size.
The StringBuilder will only be a "long life" object if it's used as
such - which it isn't very often, in my experience.
As the objet is living a bit longer it can be pushed in generation 1
where it will be destroyed later than in generation 0 (as short living
strings)...
Again, only if it actually lives longer. If enough memory is required
during the concatenation to force a GC to push the StringBuilder into
gen1, then the same memory pressure would have pushed one of the
temporary strings into gen1 when using string concatenation too.
So, if it is very simple to find good samples that show where
StringBuilder is, with no doubt, the best solution, there are plenty of
real situations where the StringBuilder will not be the best solution.
concatenation of short living strings is often better (more often lot
of people is thinking).

Extreme cases are easy to understand, but extreme cases are also less
common in daily development... So don't be too much fool by the
"stringbuil der effiency myth".
There are certainly myths around this topic (as I mention in my
article) but your reasoning above about GC generations just doesn't
hold water in my view. Note that by using StringBuilder you usually (in
typical realistic cases for StringBuilder) use less memory than by
concatenation anyway, so the GC is less likely to *need* to push
anything up to gen1.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 24 '08 #7
OD
There are certainly myths around this topic (as I mention in my
article) but your reasoning above about GC generations just doesn't
hold water in my view. Note that by using StringBuilder you usually (in
typical realistic cases for StringBuilder) use less memory than by
concatenation anyway, so the GC is less likely to *need* to push
anything up to gen1.
I'm sure you tested string vs SB, and you saw, like me, that things are
not as simple as saying "SB is ever the best solution". That's only
what I mean.
And, of course, I'm not saying that SB is useless and must not be used!
I'm just saying that more than often a "normal" code is just on the
edge, an area where deciding than SB is "certainly" the best solution
is not as obvious as it seems.
And what I'm trying to explain is "do not follow the 'pensée
unique'(*)" and test by yourself to see where and when SB is really
best than string concatenation.

(*) can be translated by "single thought".

--
OD___
www.e-naxos.com
Sep 24 '08 #8
OD <OD <webmaster @ e-naxos dot com>wrote:
There are certainly myths around this topic (as I mention in my
article) but your reasoning above about GC generations just doesn't
hold water in my view. Note that by using StringBuilder you usually (in
typical realistic cases for StringBuilder) use less memory than by
concatenation anyway, so the GC is less likely to *need* to push
anything up to gen1.
I'm sure you tested string vs SB, and you saw, like me, that things are
not as simple as saying "SB is ever the best solution". That's only
what I mean.
Which is why I have the caveats at the bottom of this page:
http://pobox.com/~skeet/csharp/stringbuilder.html
And, of course, I'm not saying that SB is useless and must not be used!
I'm just saying that more than often a "normal" code is just on the
edge, an area where deciding than SB is "certainly" the best solution
is not as obvious as it seems.
But the logic you used for that was flawed. I think it's entirely
reasonable to use StringBuilder for every case where you've got a loop
and are building up a string. Where it's slower, it'll only be very
marginally slower - but where it's faster, it might be very much
faster.
And what I'm trying to explain is "do not follow the 'pensée
unique'(*)" and test by yourself to see where and when SB is really
best than string concatenation.

(*) can be translated by "single thought".
Well, I think the rules of thumb at the bottom of the page linked above
are quite reasonable - you don't need everyone testing their individual
situation every time they need to build a string in a loop.

Beyond that, I was mostly rebutting your flawed logic about the GC and
how StringBuilders end up being more expensive because of being pushed
to gen1.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 24 '08 #9
OD
>
Which is why I have the caveats at the bottom of this page:
http://pobox.com/~skeet/csharp/stringbuilder.html
I was not commented your web page, of course, just the messages in this
post.
Well, I think the rules of thumb at the bottom of the page linked above
are quite reasonable - you don't need everyone testing their individual
situation every time they need to build a string in a loop.
I just "half" agree : of course you can't ask everyone to test
everything, we all have to trust some "experts" cause one live is not
enough if we have to test everything. This is the "half" I agree, it's
a kind of pattern and seems to be reasonable.
The other half of the way is, on an individual point of view, that you
must not trust any (self-proclaimed or not) expert until you test
things by yourself. Testing things is the best school to understand.
So, finally, trusting others tests is just a stopgap because our time
on earth is limited, and when it's possible, of course, we all have to
test everything...

Beyond that, I was mostly rebutting your flawed logic about the GC and
how StringBuilders end up being more expensive because of being pushed
to gen1.
it's not flawed. You must say "I don't believe it". It's just a
believing problem, not a technical one. Or that means you're saying
"i'm the expert, not you". Perhaps it's true, perhaps not...
As I know what I say, I can just ask you to test a little bit more and
you'll see.

--
OD___
www.e-naxos.com
Sep 27 '08 #10

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

Similar topics

6
1614
by: Jax | last post by:
Custom control problem. I'm modding a textbox so that it will always have a "%" sign at the end of it. I have overrided the Text property to account for the "%" value within the textbox and have add BaseText to give access to the baseText method too. I have the text_changed event handler wired up to this method, problem is that it works ONLY every other time. The statement that works every other time is this:
26
3206
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: http://hardywang.1accesshost.com ICQ: 3359839 yours Hardy
15
50258
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
4
3616
by: screamer81 | last post by:
Hello, I've a SDK functions description for a scanner and I try to convert unmanaged DLL C++ functions to c#. I converted all except one of them. This function is getting a struct parameter. int WINAPI ImgSave(_T_Scan_Param *ScanP, unsigned char *szMicr, int *num_chars, int y0, int y1, int cOcrCode_option) struct _T_Scan_Param { char file1;
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.