java - 关于 String 实例化的最佳实践好奇心

标签 java string instantiation

<分区>

我正在阅读一些关于 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==btrue !

只有当字符串还没有被驻留时,才会创建。 第一次会创建一个对象,它会存储在一个叫做字符串常量池的地方。

但是使用 new 将为每个字符串创建不同的对象,将输出 false

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

现在 a==bfalse

因此,当使用字面量时,它更易于阅读,编译器也更容易进行优化。所以..尽可能使用它。

关于java - 关于 String 实例化的最佳实践好奇心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646188/

相关文章:

java - 鼠标事件,不在 Jframe 上

java - 从自定义 ListView 元素中的 Spinner getSelectedItem

string - 在scala中使用本地化对字符串列表进行排序

Python 用括号分割字符串

c++ - C++11标准中实例化单元的含义是什么?

绘图时 Java Swing NullPointerException

java - 对并发架构概念的困惑

java - 基于分隔符 java 从加密文件中读取行

java - 实例化一个类,在java中传递?

java - 如何使用数组将实例化对象用作方法的参数