I have been told that creating String instance like this
String s = new String("Don't do this"); // explicit
has a performance problem since it creates two instance of string on for double quoted phrase "Don't do this" and one for the new String() constructor!
today i had the time to test it by my self I created two classes:
public class String1 {
public static void main(String[] args) {
String s = new String("Hello");
System.out.println(s);
}
}
public class String2 {
public static void main(String[] args) {
String s = "Hello";
System.out.println(s);
}
}
here is the output of javap:
C:\jav>javap String1
Compiled from "String1.java"
public class String1 extends java.lang.Object{
public String1();
public static void main(java.lang.String[]);
}
C:\jav>javap String2
Compiled from "String2.java"
public class String2 extends java.lang.Object{
public String2();
public static void main(java.lang.String[]);
}
seems they are same however with the -c flag the outputs are deferent.
C:\jav>javap -c String1
Compiled from "String1.java"
public class String1 extends java.lang.Object{
public String1();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2; //class java/lang/String
3: dup
4: ldc #3; //String Hello
6: invokespecial #4; //Method java/lang/String."<init>":(Ljava/lang/String;)V
9: astore_1
10: getstatic #5; //Field java/lang/System.out:Ljava/io/PrintStream;
13: aload_1
14: invokevirtual #6; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: return
}
C:\jav>javap -c String2
Compiled from "String2.java"
public class String2 extends java.lang.Object{
public String2();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String Hello
2: astore_1
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: aload_1
7: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
10: return
}
so here is my questions :) first what is "ldc", astore_1 etc ? are there any documentation describing those? second does javac really can't figure out these two sentences are equal??