加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:08:42 所属栏目:Java 来源:网络整理
导读:参见英文答案 Strings are objects in Java,so why don’t we use ‘new’ to create them?????????????????????????????????????14个 我正在阅读有关java最佳实践的一些建议,我得到了以下想法让我很好奇 此外,无论何时想要实例化String对象,都不要使用其构
参见英文答案 > Strings are objects in Java,so why don’t we use ‘new’ to create them?????????????????????????????????????14个
我正在阅读有关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是真的!

只有在尚未实现的情况下才会创建字符串.
将在第一次创建对象,并将其存储在称为String常量池的位置.

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

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

现在a == b是假的.

因此,在使用文字时,它更容易阅读,并且编译器更容易进行优化.所以..尽可能使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读