Saturday, 25 March 2017

java - Best practice curiosity regarding String instantiation

Answer


Answer





I was reading some advices about best practices in java and I got the following idea which made me curious



Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly.



For example:



//slow instantiation
String slow = new String("Yet another string object");


//fast instantiation
String fast = "Yet another string object";


Why is this? doesn't the 'fast' call the default string constructor?


Answer



When you use new you get a new string object, but if you use string literal then see here:




In computer science, string interning is a method of storing only one

copy of each distinct string value, which must be immutable. Interning
strings makes some string processing tasks more time- or
space-efficient at the cost of requiring more time when the string is
created or interned. The distinct values are stored in a string intern
pool. The single copy of each string is called its 'intern' and is
typically looked up by a method of the string class, for example
String.intern() in Java. All compile-time constant strings in Java are
automatically interned using this method.





If you do:



String a = "foo";
String b = "foo";


Then a==b is true !



A String will be created only if it hasn't been interned.
An object will be created in the first time, and it'll be stored in a place called the String constant pool.




But using the new which will create a different object for each string, will output false.



String a = new String("foo");
String b = new String("foo");


Now a==b is false.



So when using literal it is easier to read, plus easier for the compiler to make optimizations. So.. use it when you can.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...