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

前端 未结 3 981
[愿得一人]
[愿得一人] 2020-12-03 02:37

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

Example from MSDN:

String s1 = \"MyTest\";
String s2 = new StringBuilder().Append(\         


        
3条回答
  •  無奈伤痛
    2020-12-03 03:21

    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

提交回复
热议问题