Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

You can't beat

return "Hello, " + username;

if your scenario is really that simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top