StringBuilder buffer allocation support in compiler

Vicente-Arturo Romero-Zaldivar vicente.romero at oracle.com
Thu Jun 5 19:33:01 UTC 2014


Hi Laszlo,

On 05/06/14 20:27, Laszlo Hornyak wrote:
> Hi,
>
> Given this sample code
>
>     public static String sayHello(String name, int age) {
>         return "Hello " + name + ", this is your " + age + "th birthday";
>     }
>
> The compiler will generate this bytecode:
>        0: new           #11                 // class 
> java/lang/StringBuilder
>        3: dup
>        4: invokespecial #12                 // Method 
> java/lang/StringBuilder."<init>":()V
>        7: ldc           #19                 // String Hello
>        9: invokevirtual #15                 // Method 
> java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
>       12: aload_0
>       13: invokevirtual #15                 // Method 
> java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
>       16: ldc           #20                 // String , this is your
>       18: invokevirtual #15                 // Method 
> java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
>       21: iload_1
>       22: invokevirtual #13                 // Method 
> java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
>       25: ldc           #21                 // String th birthday
>       27: invokevirtual #15                 // Method 
> java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
>       30: invokevirtual #17                 // Method 
> java/lang/StringBuilder.toString:()Ljava/lang/String;
>       33: areturn
>
> The most interesting line is:
>        4: invokespecial #12                 // Method 
> java/lang/StringBuilder."<init>":()V
>
>
> Since all the string literals are given for the compiler, it could 
> give an estimation on the required buffer size to the StringBuilder 
> constructor. In this example the string literals already take 32 
> characters, plus a string representation of an integer takes up to 12 
> characters. The String size is 0 to Integer.MAX_VALUE, but 16 might be 
> a good default. In this case a constructor call could be generated to 
> allocate a buffer with 50 characters and some (possibly all) buffer 
> re-allocation could be saved in the subsequent append calls.
> The performance gain seems to be significant since the subsequent 
> buffer allocations can take up to 30-40 percent of the execution time.

Just curious, do you have a proof for this?

> Is there a specific reason for the java compiler not to support 
> pre-allocation of StringBuilder buffer based on string literals and 
> parameters?
>
> Thank you,
> Laszlo
>
>
> -- 
>
> EOF
Thanks,
Vicente


More information about the compiler-dev mailing list