views:

97

answers:

4

I'm curious. The scenario is a web app/site with e.g. 100's of concurrent connections and many (20?) page loads per second.

If the app needs to server a formatted string

string.Format("Hello, {0}", username);

Will the "Hello, {0}" be interned? Or would it only be interned with

string hello = "Hello, {0}";
string.Format(hello, username);

Which, with regard to interning, would give better performance: the above or,

StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);

or even

string hello = "Hello, {0}";
StringBuilder builder = new StringBuilder()
builder.Append("Hello, ");
builder.Append(username);

So my main questions are: 1) Will a string.Format literal be interned 2) Is it worth setting a variable name for a stringbuilder for a quick lookup, or 3) Is the lookup itself quite heavy (if #1 above is a no)

I realise this would probably result in minuscule gains, but as I said I am curious.

+1  A: 

Quick answer: run a 100k iterations and find out.

Chris Lively
+5  A: 

There is a static method String.IsInterned(str) method. You could do some testing and find out!

http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx

John Buchanan
ah, right. I didn't know about that one, thanks.
David Archer
+3  A: 

String.Format actually uses a StringBuilder internally, so there is no reason to call it directly in your code. As far as interning of the literal is concerned, the two code versions are the same as the C# compiler will create a temporary variable to store the literal.

Finally, the effect of interning in a web page is negligible. Page rendering is essentially a heavy-duty string manipulation operation so the difference interning makes is negligible. You can achieve much greater performance benefits in a much easier way by using page and control caching.

Panagiotis Kanavos
How is it you have so few points? Great answer :-)
David Archer
even though String.Format uses an string Builder to concatenate the string it still needs to parse the formatstring for its parameters.
Sven Hecht
The alternative is to build the string step by step, creating code that is harder to write, read and maintain. The performance gain is too small to justify this. There are other, far more useful ways to improve performance like output caching.
Panagiotis Kanavos
A: 

You can't beat

return "Hello, " + username;

if your scenario is really that simple.

StarBright
that's not true. StringBuilder and String.Concat() both are MUCH faster.
Sven Hecht