I'd expect the JITted code to be pretty much the same. In the bytecode there's an extra store/load for the first form, but I'd be very surprised to see that make a real difference. The advantage of the first form is that it can make debugging easier - but it makes the code more verbose at the same time.
EDIT: I originally wrote that the two create the same bytecode, but that's not true:
public class Test {
static void separate() {
String x = "hello";
String y = x.toString();
foo(y);
}
static void combined() {
String x = "hello";
foo(x.toString());
}
static void foo(String x) {
}
}
Compiles to (just the separate
and combined
methods):
static void combined();
Code:
0: ldc #2; //String hello
2: astore_0
3: aload_0
4: invokevirtual #3; //Method java/lang/String.toString:()Ljava/lang/String;
7: invokestatic #4; //Method foo:(Ljava/lang/String;)V
10: return
static void separate();
Code:
0: ldc #2; //String hello
2: astore_0
3: aload_0
4: invokevirtual #3; //Method java/lang/String.toString:()Ljava/lang/String;
7: astore_1
8: aload_1
9: invokestatic #4; //Method foo:(Ljava/lang/String;)V