What happens during compilation and runtime when concatenating an empty string in Java?

This is a question that arose mainly out of sheer curiosity (and kills for a while). I specifically ask about Java for the sake of specificity.

What happens in memory if I concatenate a string (any string) with an empty string, for example:

String s = "any old string";
s += "";

I know that after that the contents of s will still be "any old line", since an empty ASCII line is stored in memory as just an ASCII zero (since at least in Java lines always end with zero), but I'm curious find out if Java (the compiler? VM?) performs enough optimization to know that s will not change, and it can just completely omit this instruction in bytecode or something else happens during compilation and startup.

+5
source share
2 answers

This is a bytecode time!

class EmptyString {
    public static void main(String[] args) {
        String s = "any old string";
        s += "";
    }
}

javap -c EmptyString:

Compiled from "EmptyString.java"
class EmptyString extends java.lang.Object {
EmptyString ();
  Code:
   0: aload_0
   1: invokespecial # 1; // Method java / lang / Object. "" :() V
   4: return

public static void main (java.lang.String []);
  Code:
   0: ldc # 2; // String any old string
   2: astore_1
   3: new # 3; // class java / lang / StringBuilder
   6: dup
   7: invokespecial # 4; // Method java / lang / StringBuilder. "" :() V
   10: aload_1
   11: invokevirtual # 5; // Method java / lang / StringBuilder.append: (Ljava / lang / String;) Ljava / lang / StringBuilder;
   14: ldc # 6; // String
   16:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   19:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   22:  astore_1
   23:  return

}

, += StringBuilder , , .

, , :

class EmptyString {
    public static void main(String[] args) {
        String s = "any old string" + "";
    }
}

javap -c EmptyString:

Compiled from "EmptyString.java"
class EmptyString extends java.lang.Object{
EmptyString();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   ldc     #2; //String any old string
   2:   astore_1
   3:   return

}
+16

s += "";

Java String s . eclipse handy ( , NetBeans, - eclipse), , s . s id = 20, id = 24.

+2

All Articles