Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String optimisation

How many Strings does this create?

String test(String text) {
  return "string 1 " +
    text + " string 2 " +
    "string 3";
}
like image 912
Michael Avatar asked Dec 17 '22 14:12

Michael


2 Answers

No new String calls are present here, the only one that exists is in StringBuilder.toString, so

1

java.lang.String test(java.lang.String);
  Code:
   Stack=3, Locals=2, Args_size=2
   0:   new #16; //class java/lang/StringBuilder
   3:   dup
   4:   ldc #18; //String string 1 
   6:   invokespecial   #20; //Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
   9:   aload_1
   10:  invokevirtual   #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   13:  ldc #27; //String  string 2 
   15:  invokevirtual   #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   18:  ldc #29; //String string 3
   20:  invokevirtual   #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   23:  invokevirtual   #31; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   26:  areturn
like image 59
MeBigFatGuy Avatar answered Jan 01 '23 21:01

MeBigFatGuy


This is pretty easy to answer by compiling the code, then inspecting the bytecode with javap -c. In this particular case, the compiler should generate code like

String result = new StringBuilder("string1").
    append(text).append("string2").append("string3").toString();

so depending on how you look at it, you might say only one, or if you're one of those people who likes to count literals as being "created" when they're used, you could say four.

like image 38
Ernest Friedman-Hill Avatar answered Jan 01 '23 21:01

Ernest Friedman-Hill