Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Should I use a StringBuilder? 1

Status
Not open for further replies.

Nelviticus

Programmer
Sep 9, 2003
1,819
0
36
GB
I know that if you're intending to modify a string after you've created it you should use a StringBuilder. However, if you're creating a string that is made up of components or split across lines like this:

Code:
string sQuery;
sQuery = "SELECT COUNT(C.CLIENT_CODE) "
	+ "FROM HBM_CLIENT C "
	+ "WHERE C.ENTITY_TYPE='"
	+ sType
	+ "'";

is it still better to use a StringBuilder?

Thanks

Nelviticus
 
Two things:

1. Yes, use a StringBuilder in situations like this. Your code will run slightly faster and use less memory.

2. Don't use string concatenation to build SQL -- very unsafe. See:

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
hey,

If you aren't going to be doing a lot of modifications to your string, ie. keep setting it equal to something different, then I wouldn't worry about it. Mostly worry about using string builder in the situations where you have to do a lot of manipulation, since it handles resizing itself for memory. The regular string class will have to keep allocating new memory blocks every time manipulations are done, this wouldn't be a problem, but it doesn't release the unneeded memory after it is done, so you can end up with a runaway memory leak very easily just by using a loop (trust me, we have discovered this from experience).

Good luck,
Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
Thanks. I know it won't make a huge amount of difference when something is performed only once, but I'd rather do things the efficient way. I wasn't sure whether concatenating a string with variables on initialisation would cause the same problems as appending things to a string, but on thinking about it I suppose it must.

Thanks for the info on SQL Chip - I'll have a read.

Nelviticus
 
so what is the deal with "\" as a new line?
and how do you place a \ in a string?

...do you use "\\" ?

I saw this code at:
For example, consider the differences between the String and StringBuilder classes. Examine this code from my Mandelbrot application:
Code:
String msg = "This shows the \ 
	Mandelbrot Set from the Range:";
msg += "\nx=("+minX.ToString () 
	+","+maxX.ToString ()+")";
msg += "\ny=("+minY.ToString() 
	+","+maxY.ToString ()+")";
msg += "\nEach Pixel represents ("+ 
	scaleX.ToString ()+","+
	scaleY.ToString ()+")";

String is a different animal. Each time the msg string is assigned a new value, a new string is created. You can write this more efficiently using the StringBuilder class:
Code:
StringBuilder msg = new StringBuilder 
	("This shows the Mandelbrot Set \	
	from the Range:");
msg.AppendFormat ("\nx={0:e4}, 
	{1:e4})\ny=({2:e4}, {3:e4})",
	minX, maxX, minY, maxY);
msg.AppendFormat ("\nEach Pixel \
	represents ({0:e4},{1:e4})", 
	scaleX, scaleY);
System.WinForms.MessageBox.Show 
	(msg.ToString());

for the original question, could you say:
string sQuery;
Code:
sQuery = "SELECT COUNT(C.CLIENT_CODE) \
    FROM HBM_CLIENT C \
    WHERE C.ENTITY_TYPE='"
    + sType
    + "'";

Also, String and StringBuilder are Unicode... right?
What do you have to do if an external function requires ASCII? is it cast to an ascii string automatically?

Have Fun, Be Young... Code BASIC
-Josh

cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
I tried using a backslash to split my lines but my compiler (VS.Net 2003) doesn't seem to like it. It gives me a "new line in constant" error.

Nelviticus
 
Code:
string sPath="C:\\temp\\myfile.txt";
// or
sPath = @"C:\temp\myfile.txt"
object[] arr = sPath.Split('\\');
will produce the following string objects:
C:
temp
myfile.txt

-obislavu-
 
That's what I was talking about above...

Like if you said:
Code:
String S = "This \
            Is \
            A \
            String";

it would be the same as...
Code:
String S = "This Is A String";

Right?

So does...
Code:
string sPath="C:\\temp\\myfile.txt";

set the string to: "C:\temp\myfile.txt" ?

Have Fun, Be Young... Code BASIC
-Josh

cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
The backslash character is an escape character in C# strings. You can use it to split lines, or insert linefeeds, returns, etc: \n \r

In order to get a true backslash character, you can either:

1. Double them up: "c:\\myfile.txt"
2. Put an @ symbol in front of the string: @"c:\myfile.txt"

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Josh, my question has been answered so this is purely academic but if I have:

Code:
String S = "This \
            Is \
            A \
            String";

the lines are underlined in red and if I try to build it I get a compiler error as mentioned above.

Nelviticus
 
that's what I thought too...

Something in the help files, or on the net, threw me off...

for Example, in C# 2005 help files...

You can also use the backslash (\) as a continuation character. When a newline character (equivalent to pressing the RETURN key) immediately follows the backslash, the compiler ignores the backslash and the newline character and treats the next line as part of the previous line. This is useful primarily for preprocessor definitions longer than a single line. For example:
Code:
#define assert(exp) \
( (exp) ? (void) 0:_assert( #exp, __FILE__, __LINE__ ) )

But that is not a string

but this code, same as listed in my first post, shows the character used the same way in a string...
For example, consider the differences between the String and StringBuilder classes. Examine this code from my Mandelbrot application:
Code:
String msg = "This shows the \ 
	Mandelbrot Set from the Range:";
msg += "\nx=("+minX.ToString () 
	+","+maxX.ToString ()+")";
msg += "\ny=("+minY.ToString() 
	+","+maxY.ToString ()+")";
msg += "\nEach Pixel represents ("+ 
	scaleX.ToString ()+","+
	scaleY.ToString ()+")";

And I could have sworn it worked the other day, but I know it is not working now (newline in constant error)
So... I dunno... Maybe I just needed some sleep :p

Have Fun, Be Young... Code BASIC
-Josh

cubee101.gif


PROGRAMMER: (n) Red-eyed, mumbling mammal capable of conversing with inanimate objects.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top