Optimize string concatenations

Issue #280 new
Jesper Öqvist
created an issue

When several strings are concatenated in a row with +=, ExtendJ creates a new StringBuilder object to add each new string to the result.

This is unnecessary, especially for straight-line code without method calls.

Reusing a StringBuilder when there are method calls may not be safe if the called method can modify the partially built string (if the result is to be stored in a field).

Demonstration:

public class Test {
  public static void main(String[] args) {
    String message = "x";
    message += " marks ";
    message += "the spot";
    System.out.println(message);
  }
}

ExtendJ-generated bytecode:

         0: ldc           #20                 // String x
         2: astore_1
         3: aload_1
         4: new           #22                 // class java/lang/StringBuilder
         7: dup
         8: invokespecial #23                 // Method java/lang/StringBuilder."<init>":()V
        11: swap
        12: invokevirtual #27                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        15: ldc           #29                 // String  marks
        17: invokevirtual #27                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        20: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        23: astore_1
        24: aload_1
        25: new           #22                 // class java/lang/StringBuilder
        28: dup
        29: invokespecial #23                 // Method java/lang/StringBuilder."<init>":()V
        32: swap
        33: invokevirtual #27                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        36: ldc           #35                 // String the spot
        38: invokevirtual #27                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        41: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        44: astore_1
        45: getstatic     #41                 // Field java/lang/System.out:Ljava/io/PrintStream;
        48: aload_1
        49: invokevirtual #47                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
        52: return

Comments (0)

  1. Log in to comment