Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .NET create a string intern pool for each assembly?

I have a situation where I will encounter lots of duplicate strings which will persist in memory for a long time. I want to use String.Intern but I don't want to invade any potential application resources since my project is a library. How does this work?

like image 586
toplel32 Avatar asked Oct 24 '14 09:10

toplel32


People also ask

Does C# have string pool?

String objects created by directly assigning a String literal are stored in the String intern pool table. Dynamically created String objects are stored in the normal memory part on the heap.

How do string interns work?

intern() The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

Where is string intern pool?

The distinct values are stored in a string intern pool. The single copy of each string is called its intern and is typically looked up by a method of the string class, for example String. intern() in Java. All compile-time constant strings in Java are automatically interned using this method.

What is string intern () When and why should it be used?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.


1 Answers

The intern table for strings is CLR-scoped:

First, the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned String object can persist after your application, or even your application domain, terminates.

So not only the intern table is not assembly-specific, but it can outlive your assembly. The good news is that duplicated strings won't be a problem since same literal strings exist with the same reference once interned. So Interning is recommended:

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

string s1 = "MyTest"; 
string s2 = new StringBuilder().Append("My").Append("Test").ToString(); 
string s3 = String.Intern(s2); 
Console.WriteLine((Object)s2==(Object)s1); // Different references.
Console.WriteLine((Object)s3==(Object)s1); // The same reference.
like image 194
samy Avatar answered Oct 20 '22 20:10

samy