0

Possible Duplicate:
string memory allocation

What is the difference between

System.out.println("hello world");
System.out.println("hello world");

and

String s="hello world";
System.out.println(s);
System.out.println(s);

and which one is better?

Community
  • 1
  • 1
kaka
  • 7,425
  • 4
  • 19
  • 23

4 Answers4

2

None, they compile to almost the same bytecode (only difference is the variable reference). No memory difference (except the variable reference).

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
1

Code-quality-wise it is better to define repeating strings as constants:

public static final String HELLO_WORLD = "hello world";

As for the memory - no difference.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

In this particular case, they are both identical. Constant strings are intern'ed by the VM so that they both point to the same String object.

In general, once a string is computed, it's best to assign it to a field/variable and reuse it. (I guess this applies in general - reuse computation results when there is no change, rather than repeating the computation.)

For string constants, I usually move them into static constant fields. There's no performance gain, but it avoids having "magic values" in your code. Similarly, UI messages should ideally be moved out of the code and put into properties bundles.

mdma
  • 56,943
  • 12
  • 94
  • 128
0

On my mind, the Java compiler will optimize the code and there won't be any difference between the two solutions.

The code optimization in javac does not worth the optimizations of gcc but it should be enough efficient for this kind of things. You may look into "constant folding" optimization in Java (but I am not sure). You could also take a look at this article.

ThR37
  • 3,965
  • 6
  • 35
  • 42