Java – Best Practices for string instantiation

So why don't we use 'new' to create them? 14

In addition, whenever you want to instantiate a string object, do not 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? Isn't 'fast' calling the default string constructor?

Solution

When you use new, you will get a new string object, but if you use string text, see here:

If you do this:

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

Then a = = B is true!

Strings are created only if they have not been implemented The object is created the first time and stored in a location called the string constant pool

But using new will create a different object for each string and output false

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

Now a = = B is false

Therefore, when using text, it is easier to read and the compiler is easier to optimize So Use it whenever possible

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>