Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interning. How does the compiler know?

I know what string interning is, and why the following code behaves the way it does:

var hello = "Hello";
var he_llo = "He" + "llo";
var b = ReferenceEquals(hello, he_llo); //true

Or

var hello = "Hello";
var h_e_l_l_o = new string(new char[] { 'H', 'e', 'l', 'l', 'o' });
var b = ReferenceEquals(hello, he_llo); //false

...or I thought I did, because a subtle bug has cropped up in some code I'm working on due to this:

var s = "";
var sss = new string(new char[] { });
var b = ReferenceEquals(s, sss); //True!?

How does the compiler know that sss will in fact be an empty string?

like image 808
InBetween Avatar asked Jan 27 '17 13:01

InBetween


People also ask

How do string interns work?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

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).

What is string interning why it Python have it?

String Interning is a process of storing only one copy of each distinct string value in memory. This means that, when we create two strings with the same value - instead of allocating memory for both of them, only one string is actually committed to memory. The other one just points to that same memory location.

What is the use of intern method of string in Java?

The Java String class intern() method returns the interned string. It returns the canonical representation of string. It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.


1 Answers

If an empty array or null array is passed in a string constructor then it returns an empty string.

It is specified in a comment in the reference code.

 // Creates a new string with the characters copied in from ptr. If
 // ptr is null, a 0-length string (like String.Empty) is returned.

You can also see the same result with null array like:

char[] tempArray = null;
var s = "";
var sss2 = new string(tempArray);
var b = ReferenceEquals(s, sss2); //True!?
like image 63
Habib Avatar answered Sep 25 '22 01:09

Habib