473,608 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when to use StringBuilder

I read somewhere that if you are concatenating more than 2 or 3 strings
you should use StringBuilder as it will use up less resources. Does
this apply when you are building up a string (for example an SQL query
or some XML)?

This is an example of some of my current code :

strReturnedXML = "<?xml version=\"1.0\" ?>";
strReturnedXML += "<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">";
strReturnedXML += "<auth>";
strReturnedXML += "<cug>" + strCUG + "</cug>";
strReturnedXML += "<pasw>" + strPasw + "</pasw>";
strReturnedXML += "</auth>";
strReturnedXML += "<ok>";
strReturnedXML += "<mess-id>request</mess-id>";
strReturnedXML += "<number>44 " + strNextNumberLe ssZero + "</number>";

if (strRequestPay == "card")
{
strReturnedXML += "<pin>054" + strRequestSeria l + strPIN + "</pin>";
}

strReturnedXML += "</ok>";
strReturnedXML += "</vcn-rsp>";

Would I save resources by doing it this way instead?

StringBuilder sbdReturnedXML = new StringBuilder(4 00);

sbdReturnedXML. Append("<?xml version=\"1.0\" ?>");
sbdReturnedXML. Append("<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">");
sbdReturnedXML. Append("<auth>" );
sbdReturnedXML. Append("<cug>" + strCUG + "</cug>");
sbdReturnedXML. Append("<pasw>" + strPasw + "</pasw>");
sbdReturnedXML. Append("</auth>");
sbdReturnedXML. Append("<ok>");
sbdReturnedXML. Append("<mess-id>request</mess-id>");
sbdReturnedXML. Append("<number >44" + strNextNumberLe ssZero +
"</number>");

if (strRequestPay == "card")
{
sbdReturnedXML. Append("<pin>05 4" + strRequestSeria l + strPIN +
"</pin>");
}

sbdReturnedXML. Append("</ok>");
sbdReturnedXML. Append("</vcn-rsp>");
Any assistance would be really appreciated.
Cheers,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
7 2098
Hi Mike,

Yes, any kind of medium to large string addition will benefit from a StringBuilder. What the content of the string is does not matter.

--
Happy coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #2
Yes, StringBuilder is a much more efficient way to do this - if you use the
+ operator with a string class as you are doing below a new string is
allocated on every call. Another point is that for creating xml strings like
this you may want to look at XmlTextWriter as this gives extra functionality
for building xml, although StringBuilder will certainly work fine for this.

--
Steve Willcock (MCSD for Microsoft.NET)
http://www.willcockconsulting.com/

"Mike P" <mr*@telcoelect ronics.co.uk> wrote in message
news:uQ******** *****@tk2msftng p13.phx.gbl...
I read somewhere that if you are concatenating more than 2 or 3 strings
you should use StringBuilder as it will use up less resources. Does
this apply when you are building up a string (for example an SQL query
or some XML)?

This is an example of some of my current code :

strReturnedXML = "<?xml version=\"1.0\" ?>";
strReturnedXML += "<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">";
strReturnedXML += "<auth>";
strReturnedXML += "<cug>" + strCUG + "</cug>";
strReturnedXML += "<pasw>" + strPasw + "</pasw>";
strReturnedXML += "</auth>";
strReturnedXML += "<ok>";
strReturnedXML += "<mess-id>request</mess-id>";
strReturnedXML += "<number>44 " + strNextNumberLe ssZero + "</number>";

if (strRequestPay == "card")
{
strReturnedXML += "<pin>054" + strRequestSeria l + strPIN + "</pin>";
}

strReturnedXML += "</ok>";
strReturnedXML += "</vcn-rsp>";

Would I save resources by doing it this way instead?

StringBuilder sbdReturnedXML = new StringBuilder(4 00);

sbdReturnedXML. Append("<?xml version=\"1.0\" ?>");
sbdReturnedXML. Append("<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">");
sbdReturnedXML. Append("<auth>" );
sbdReturnedXML. Append("<cug>" + strCUG + "</cug>");
sbdReturnedXML. Append("<pasw>" + strPasw + "</pasw>");
sbdReturnedXML. Append("</auth>");
sbdReturnedXML. Append("<ok>");
sbdReturnedXML. Append("<mess-id>request</mess-id>");
sbdReturnedXML. Append("<number >44" + strNextNumberLe ssZero +
"</number>");

if (strRequestPay == "card")
{
sbdReturnedXML. Append("<pin>05 4" + strRequestSeria l + strPIN +
"</pin>");
}

sbdReturnedXML. Append("</ok>");
sbdReturnedXML. Append("</vcn-rsp>");
Any assistance would be really appreciated.
Cheers,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #3
That's just what I thought....chee rs Morten, Steve!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
The task that I'm mainly using the StringBuilder object for
is when constructing long query strings in SQL. As I'm now doing this
via the StringBuilder, when I create an SQLCommand object, I now how to
convert the StringBuilder to a string. Would I still be making
performance gains even though at the end of building the StringBuilder I
still have to convert to a string?
SqlCommand objCommand = new
SqlCommand(sbdU pdateAttemptedP urchase.ToStrin g(), objConnection);
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #5
Yes, as you are still allocating less objects - if you are adding strings
together you are actually allocating a new string object every time.

Steve

"Mike P" <mr*@telcoelect ronics.co.uk> wrote in message
news:OO******** ******@tk2msftn gp13.phx.gbl...
The task that I'm mainly using the StringBuilder object for
is when constructing long query strings in SQL. As I'm now doing this
via the StringBuilder, when I create an SQLCommand object, I now how to
convert the StringBuilder to a string. Would I still be making
performance gains even though at the end of building the StringBuilder I
still have to convert to a string?
SqlCommand objCommand = new
SqlCommand(sbdU pdateAttemptedP urchase.ToStrin g(), objConnection);
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #6
"Only time that StringBuilder is really needed is when you are concatenating
within a loop." - or when you don't know at the outset what you'll be
adding to the string. e.g. if you are building a SQL String you may have
several conditional statements where you decide whether to add extra
parameters to the WHERE clause. You won't know at the outset how many of
these parameters are going to be added or what they will be.

Steve

"Daniel Jin" <Da*******@disc ussions.microso ft.com> wrote in message
news:2A******** *************** ***********@mic rosoft.com...
actually, contrary to some belief, + on strings aren't bad for performance at all.

if you change your code to the following

strReturnedXML = "<?xml version=\"1.0\" ?>"
+ "<vcn-rsp message-id=\"" +
+ Convert.ToStrin g(bytMessageID) + "\">"
+ "<auth>"
+ "<cug>" + strCUG + "</cug>"
+ .....;

it will compile down to one call to String.Concat( string[] ). which is
actually better than StringBuilder because String.Concat calculates and
allocate a buffer that's the size of the final string length, with
StringBuilder, there might be buffer reallocations if the default length
isn't enough.

Only time that StringBuilder is really needed is when you are concatenating within a loop.

"Mike P" wrote:
I read somewhere that if you are concatenating more than 2 or 3 strings
you should use StringBuilder as it will use up less resources. Does
this apply when you are building up a string (for example an SQL query
or some XML)?

This is an example of some of my current code :

strReturnedXML = "<?xml version=\"1.0\" ?>";
strReturnedXML += "<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">";
strReturnedXML += "<auth>";
strReturnedXML += "<cug>" + strCUG + "</cug>";
strReturnedXML += "<pasw>" + strPasw + "</pasw>";
strReturnedXML += "</auth>";
strReturnedXML += "<ok>";
strReturnedXML += "<mess-id>request</mess-id>";
strReturnedXML += "<number>44 " + strNextNumberLe ssZero + "</number>";

if (strRequestPay == "card")
{
strReturnedXML += "<pin>054" + strRequestSeria l + strPIN + "</pin>";
}

strReturnedXML += "</ok>";
strReturnedXML += "</vcn-rsp>";

Would I save resources by doing it this way instead?

StringBuilder sbdReturnedXML = new StringBuilder(4 00);

sbdReturnedXML. Append("<?xml version=\"1.0\" ?>");
sbdReturnedXML. Append("<vcn-rsp message-id=\"" +
Convert.ToStrin g(bytMessageID) + "\">");
sbdReturnedXML. Append("<auth>" );
sbdReturnedXML. Append("<cug>" + strCUG + "</cug>");
sbdReturnedXML. Append("<pasw>" + strPasw + "</pasw>");
sbdReturnedXML. Append("</auth>");
sbdReturnedXML. Append("<ok>");
sbdReturnedXML. Append("<mess-id>request</mess-id>");
sbdReturnedXML. Append("<number >44" + strNextNumberLe ssZero +
"</number>");

if (strRequestPay == "card")
{
sbdReturnedXML. Append("<pin>05 4" + strRequestSeria l + strPIN +
"</pin>");
}

sbdReturnedXML. Append("</ok>");
sbdReturnedXML. Append("</vcn-rsp>");
Any assistance would be really appreciated.
Cheers,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #7
successive adding does not result in intermidate strings, contrary to some
belief. but adding and assigning like shown in the original post will. see
my other post below.

"Steve Willcock" wrote:
Yes, as you are still allocating less objects - if you are adding strings
together you are actually allocating a new string object every time.

Steve

"Mike P" <mr*@telcoelect ronics.co.uk> wrote in message
news:OO******** ******@tk2msftn gp13.phx.gbl...
The task that I'm mainly using the StringBuilder object for
is when constructing long query strings in SQL. As I'm now doing this
via the StringBuilder, when I create an SQLCommand object, I now how to
convert the StringBuilder to a string. Would I still be making
performance gains even though at the end of building the StringBuilder I
still have to convert to a string?
SqlCommand objCommand = new
SqlCommand(sbdU pdateAttemptedP urchase.ToStrin g(), objConnection);
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


Nov 16 '05 #8

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

Similar topics

8
1584
by: | last post by:
Hi! I'm very interesting in when to use exactly the StringBuilder? For example for something like this?: String strTest1 = "This"; String strTest2 = "Test"; StringBuilder stbTest = new StringBuilder(); stbTest.Append(strTest1). Append("is a "). Append(stbTest);
11
2185
by: Doug | last post by:
Is there any harm in passing an object into a method with the 'ref' keyword if the object is already a reference variable? If not, is there any benefit?
9
2450
by: Bjorn Abelli | last post by:
Hi all, When I run a normal application I can get who started a process with the following example: Process myProcesses = Process.GetProcesses(); foreach(Process p in myProcesses) { string user = p.StartInfo.EnvironmentVariables;
10
2717
by: klineb | last post by:
Good Day, I have written and utility to convert our DOS COBOL data files to a SQL Server database. Part of the process requires parsing each line into a sql statement and validting the data to keep the integrity of the database. We are parsing roughl 81 files and range in size 1 kb to 65 MB files (Average of 400,000 lines in the larger files). I have written this utility with VB.NET 2003 and when I parse all of the files I run out...
2
1676
by: m00nm0nkey | last post by:
Ok well i thought i'd try a different approach, so what I'm now trying is appending 50,000 lines from the collection to a stringbuilder, and then writing that entire stringbuilder to a file. However, look at this log: 21/04/2006 14:09:06: Building String Start 21/04/2006 14:09:14: appended 10,000 lines to the stringbuilder 21/04/2006 14:09:39: appended 10,000 lines to the stringbuilder 21/04/2006 14:10:20: appended 10,000 lines to the...
0
1880
by: firstquestion | last post by:
Hello, I need to pass a StringBuilder object to a custom unmanaged DLL. The code most of the time works great, however once in a while I get "Object reference not set to an instance of an object" which means the GC moved the address of StringBuilder object while managed code is writing to it. I have tried GC.keepalive already. GCHandle.allc and Marshal.alloc doesn't seem to be possible with this type of object. I need the equivalent of ...
10
3180
by: =?Utf-8?B?TWF0dA==?= | last post by:
I am using the following code to connect to and download files from an ftp server, but the Symantec anti-virus software on some of my customers machines tells them that their computers are attacking the Ftp server with "FTP Pathname Glob BO". See the following link for more info: http://www.symantec.com/avcenter/attack_sigs/s20430.html This is standard .Net code, so I'm not understanding why it would trigger such a response. Also,...
34
3525
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 200000 strings of 8 char each, string took over 25 minutes while StringBuilder took 40 milliseconds! Can anybody explain such a radical difference?
0
8057
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
8491
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...
0
8470
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8142
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
6010
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
5475
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
4022
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1580
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1327
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.