Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only literal strings saved in the intern pool by default?

Why by default only literal strings are saved in the intern pool?

Example from MSDN:

String s1 = "MyTest"; String s2 = new StringBuilder().Append("My").Append("Test").ToString();  String s3 = String.Intern(s2);  Console.WriteLine("s1 == '{0}'", s1); Console.WriteLine("s2 == '{0}'", s2); Console.WriteLine("s3 == '{0}'", s3); Console.WriteLine("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1);  Console.WriteLine("Is s3 the same reference as s1?: {0}", (Object)s3==(Object)s1);  /* This example produces the following results: s1 == 'MyTest' s2 == 'MyTest' s3 == 'MyTest' Is s2 the same reference as s1?: False Is s3 the same reference as s1?: True */ 
like image 224
gdoron is supporting Monica Avatar asked Dec 14 '11 17:12

gdoron is supporting Monica


People also ask

Where are interned strings stored?

Intern Strings stored in JVM heap memory In earlier java versions from 1 to 6, intern strings are stored in the Perm Generation region of the Memory. However, starting from Java 7 intern strings are stored in the Heap region (i.e. which is basically the young & old generation).

Are string literals interned?

All literal strings and string-valued constant expressions are interned.

What is String intern () method?

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.

Can we call intern method on literals?

substring(1). intern(),the method of intern() will put the ""! test". substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.


1 Answers

The short answer: interning literal strings is cheap at runtime and saves memory. Interning non-literal strings is expensive at runtime and therefore saves a tiny amount of memory in exchange for making the common cases much slower.

The cost of the interning-strings-at-runtime "optimization" does not pay for the benefit, and is therefore not actually an optimization. The cost of interning literal strings is cheap and therefore does pay for the benefit.

I answer your question in more detail here:

http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx

like image 50
Eric Lippert Avatar answered Oct 12 '22 01:10

Eric Lippert