Is str = new String ("my string") really less efficient?

I often saw people saying that they are String str = new String("my string")less efficient than writing String str = "my string",, because the first creates a static "my string" object, and then a new String object that is copied from the static.

However, given that the language here is so simple and unambiguous, it can hardly be imagined that the Java optimizer will not make any effort to simply convert the former to the latter. Why did he really decide to do this in a more laborious way? What could be any negative side effects if Java optimizes it?

+6
source share
4 answers

Take a look at the generated bytecode for String s1 = "1":

LDC "1"
ASTORE 1

And for String s2 = new String("2"):

NEW java/lang/String
DUP
LDC "2"
INVOKESPECIAL java/lang/String.<init> (Ljava/lang/String;)V
ASTORE 2

The last example is redundant and more complex. In this case, the compiler will not optimize. it is guaranteed that a new instance of the String class will be created.

With the String str = "my string"JVM, it can reuse a String instance instead of creating a new one. Consider the following examples:

String s1 = "1";
String s2 = "1";
System.out.println(s1 == s2); // true  => same reference, s1 & s2 point to the same object

String s3 = "1";
String s4 = new String("1");
System.out.println(s3 == s4); // false => s3 & s4 point to different objects
+5
source

However, given that the language here is so simple and unambiguous, it can hardly be imagined that the Java optimizer will not make any effort to simply convert the former to the latter.

First, you don’t have to write code saying that to do something slow just because you think the compiler will replace it with something faster.

-, , new .

String str = new String("my string");

, str != "my string". Java new, , String .

+9

. , 90 +% . , JIT , , ; , ? - ; .

?

, ++, . ++, , new string("some text"), Java .

, Java ?

Java escape-. String , new String , , , . . , , JIT .

+2

. - . Strings, ==, .

Java does not optimize, because there is nothing to optimize. If you use String literals, then identical ones are reduced to a single instance in the string pool, therefore

String foo = "foo";
String bar = "foo";
System.out.println(foo == bar); // True, the same object

However, with an explicit constructor

String foo = "foo";
String bar = new String("foo");
System.out.println(foo == bar); // False, bar is explicitly created as a new object with the constructor

However, since you should still use equals()objects for all associations, you will not see any difference when you run your code.

0
source

Source: https://habr.com/ru/post/1016187/


All Articles