PROPOSAL: Simplified StringBuffer/StringBuilder syntax

Joseph D. Darcy Joe.Darcy at Sun.COM
Sun Mar 29 00:22:24 PDT 2009


Gabriel Belingueres wrote:
> I compiled this code:
>
> 	String getString(List<String> baz) {
> 		int i = 2;
> 		String foo = "abcd" + "efgh";
> 		if (i % 2 == 0) {
> 			foo += "ghij" + 42 + "klmn";
> 		}
> 		for (String bar : baz) {
> 			foo += bar + "\n";
> 		}
> 		return foo;
> 	}
>
> that decompile to this:
>
>     String getString(List baz)
>     {
>         int i = 2;
>         String foo = "abcdefgh";
>         if(i % 2 == 0)
>             foo = (new
> StringBuilder(String.valueOf(foo))).append("ghij42klmn").toString();
>         for(Iterator iterator = baz.iterator(); iterator.hasNext();)
>         {
>             String bar = (String)iterator.next();
>             foo = (new
> StringBuilder(String.valueOf(foo))).append(bar).append("\n").toString();
>         }
>
>         return foo;
>     }
>
> Maybe other solution can be make the compiler smarter.
> Here, the String foo is a local variable that is used as an lvalue
> only, meaning it is always written and NEVER read (a perfect candidate
> for optimizing it creating only one StringBuilder)
>
> I'm astonished to find that the compiler didn't optimize the +=
> assignment tough.
>
>   

Generally javac lets HotSpot do the heavy lifting in terms of optimizations.

If you want to try to hack on the compiler and make it smarter, all the 
code you need is at
    http://hg.openjdk.java.net/jdk7/jdk7/langtools

-Joe



More information about the coin-dev mailing list