Internment and string equality operators

I just read this site which says: Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references...a and b do not refer to the same string instance ( http://msdn.microsoft.com/en-us/library/362314fe.aspx ).

I have not checked the interiors of the String class, but is this statement true? From what I understand, the reason for a String immutable due to string interning. In other words, for each unique value, only one copy of the string is saved. All String variables with the same values ​​refer to the same object. I thought that was why "a" == "a" works - not because it is defined to compare the values . If he checked the value, then the strings would have to be compared by nature, causing significant performance considerations and eliminating one of the main reasons that you can start string interning.

They may be too simplistic, but I find it erroneous to assume that String equality operators are defined differently than other reference types. Please correct me if I am wrong!

+4
source share
3 answers

A string can be interned, but this is optional. String literals are interned (by default - this can now be changed using the CompilationRelaxations.NoStringInterning attribute), and instances created at runtime can be, but in general not, unless special steps are taken (for example, calling String.Intern() )

There may be several instances of bites having the same meaning.

In addition, there are reasons, besides the fact that they can support strings that are immutable - immutability basically lies in the fact that objects containing links should not worry that these values ​​change “behind their backs”. Thus, it is more likely to be able to line spacing, is the result of immutability, and not the lines should be immutable so that we can intern them.

+4
source

Not all rows are interned; literals / constants from the compiler (and, in particular, the ldstr IL code) are executed automatically, and you can set / check manually, but most of the lines built at runtime (for example, from user input, loaded from files / databases or concatenation with values). So yes: you need to do value checks too.

Interning is just an optimization; he must work without him.

+2
source

No, the docs say exactly what they mean: for String s, the == operators compare string values, character by character. Just because the type of link you specify does not mean that it should compare by reference; why operator== can be overloaded .

Grumbling a little with Reflector shows that String operator==(String, String) calls Equals(String, String) , which uses unsafe pointers to compare base values.

+2
source

Source: https://habr.com/ru/post/1347983/


All Articles