0

If I have two strings with the same value, they should have the same reference, right?

here is my case:

string s1 = "aaa";
string s2 = "aaa";
Console.WriteLine(" s1: {0}; s2: {1}; equals: {2}", s1,s2, ReferenceEquals(s1, s2));

prints: s1: aaa; s2: aaa; equals: True

but take a look at this code:

string s1 = "aaa";
string s2 = new string(s1.ToCharArray());
Console.WriteLine(" s1: {0}; s2: {1}; equals: {2}", s1,s2, ReferenceEquals(s1, s2));

prints: s1: aaa; s2: aaa; equals: False

Why in the second case, the ReferenceEquals return false?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • Use `string s2 = String.Intern(new string(s1.ToCharArray()));` and try again.... http://broadcast.oreilly.com/2010/08/understanding-c-stringintern-m.html – Eser Mar 13 '16 at 00:20
  • @Valentin read about `String interning` – Eser Mar 13 '16 at 00:24
  • So you're telling me that I can have many string variables with the same value but different references? This contradicts what I knew about string pool... – Buda Gavril Mar 13 '16 at 00:26
  • 1
    Should be duplicate... Complete reference - http://csharpindepth.com/Articles/General/Strings.aspx – Alexei Levenkov Mar 13 '16 at 00:40

1 Answers1

0

I've found an answer: only literal strings are saved in the intern pool

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.

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • 1
    `saves a tiny amount of memory` In most cases it would *increase* the memory footprint of the program, not decrease it.`The cost of the interning-strings-at-runtime "optimization" does not pay for the benefit` Not true. It's very frequently not worth it, but there will be times where it'd be a big win. Because of this, you can explicitly intern strings, and it is sometimes highly beneficial to do so, it's just not done by default because it's frequently not beneficial. `The cost of interning literal strings is cheap` The cost of interning literal strings is zero; it's done at compile time. – Servy Mar 13 '16 at 02:20