MplsAmigo
MplsAmigo

Reputation: 1025

Does the CLR intern string constants?

Lately I've been reading up on how the string intern pool works. However I haven't been able to find the answer to this question.

If I declare a constant string variable like const string STR = "foo";, does this also get added to the intern table?

Upvotes: 4

Views: 435

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273429

You can find out:

const string STR = "foo";

string internedFoo = String.IsInterned("foo");    
if (internedFoo != null)  // yes it is !

The answer will be yes in any version of the framework you can find, but it is implementation dependent. And there exists an obscure setting to turn interning off.

Upvotes: 3

John Wu
John Wu

Reputation: 52280

Just to clear things up... the CLR is not involved in string interning. Interning is a compile-time concept, and the R in CLR is runtime.

Additionally, string variables are not interned. String literals are interned. A string literal is the stuff to the right, e.g.

var variable = "This is a literal.";

When the compiler notices that there is a string literal in your code, it has to add it to a resource table that is embedded in your assembly. When it adds it, it checks to see if it already exists, and if it does, it just uses the existing entry. Once compilation is complete, the entire table is emitted into the assembly, where it can be read at run-time by your code.

Upvotes: 5

Related Questions