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?
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 Intern
ing 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.
© 2022 - 2024 — McMap. All rights reserved.