我正在阅读一些关于 java 最佳实践的建议,我得到了以下让我感到好奇的想法
另外,每当你想实例化一个 String 对象时,永远不要使用它的构造函数,而总是直接实例化它。
例如:
//slow instantiation
String slow = new String("Yet another string object");
//fast instantiation
String fast = "Yet another string object";
这是为什么? 'fast' 不调用默认的字符串构造函数吗?
当您使用new
时,您会得到一个新的字符串对象,但如果您使用字符串文字,那么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.
如果你这样做:
String a = "foo";
String b = "foo";
那么 a==b
是 true !
只有当字符串还没有被驻留时,才会创建。
第一次会创建一个对象,它会存储在一个叫做字符串常量池的地方。
但是使用 new
将为每个字符串创建不同的对象,将输出 false。
String a = new String("foo");
String b = new String("foo");
现在 a==b
是 false。
因此,当使用字面量时,它更易于阅读,编译器也更容易进行优化。所以..尽可能使用它。