2

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?

MplsAmigo
  • 985
  • 6
  • 21
  • 1
    Do distinguish STR and "foo". STR is an object reference, since it is const it no longer appears in the method bodies but gets compiled in directly. "foo" is the object, a plain literal like any other and gets the interning optimization. After the compiler is done, a statement like var s = STR; is the exact equivalent to var s = "foo". – Hans Passant Feb 12 '19 at 23:01

2 Answers2

4

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • This is the most succinct and clear way I’ve seen this explained. I’m assuming then the compiler also adds string literals declared as constants? Also, I’ve read that the intern table is scoped to the CLR and is shared across applications. Is this not correct? – MplsAmigo Feb 12 '19 at 22:48
  • 1
    Resources tables are embedded in the assembly-- the DLL. So each DLL has to have their own copy. If they didn't, you wouldn't be able to distribute them separately. – John Wu Feb 13 '19 at 07:09
  • That makes sense. The confusing bit in the documentation for string.Intern is in the performance section that mentions the CLR can hold onto the intern table even after your application is terminated. – MplsAmigo Feb 15 '19 at 16:43
2

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.

H H
  • 263,252
  • 30
  • 330
  • 514