Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

.NET Strings question

In .NET (and Java), Strings are immutable. So any operations such as string.replace will not change the string object but will create a new object in the pool.

If you had a String s, and fill that with the content of a text document, and then call s.replace("\n", " "), will that create one new string in the pool or will it create as many as there are newlines?

Will a StringBuilder provide a better solution in this instance?

Hal
Wednesday, February 25, 2004

Ask yourself: would they have even provided this method if the performance was so terrible that you'd be forced to avoid it and do it yourself?

Brad Wilson (dotnetguy.techieswithcats.com)
Wednesday, February 25, 2004

The StringBuilder class is useful whenever you are going to be modifying strings a lot. For example, if you had a loop statement and you wanted to append a character to the end of a string every iteration, you would use a StringBuilder.

The primary difference is that operations that appear to modify a String object (like replace) actually are creating a new string object and returning that.

So I would say if you were just calling Replace() at the end of your method, then you should be fine performance-wise. However, if you were looping through your document line by line to build the string, you would want a StringBuilder.

And newlines and the String object are not related. A String object is a "sequential collection of System.Char objects that represents a string"

See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclasstopic.asp for more info.

CF
Wednesday, February 25, 2004

There is a very useful chapter on "Improving Managed Code Performance" available to download from: http://www.theserverside.net/booksinreview/pag.aspx

It covers strings operations in .NET amonst other things.

A sample:
"When working with strings, consider the following recommendations:
    Avoid inefficient string concatenation
    Use + when the number of appends is known
    Use StringBuilder when the number of appends is unknown
    Treat StringBuilder as a reusable buffer
    Compare string references where possible
    Use String.Intern when comparing strings multiple times in your application"

id
Thursday, February 26, 2004

*  Recent Topics

*  Fog Creek Home