views:

110

answers:

5

Hi,

I am wondering if there is any performance differences between

  1. String s = someObject.toString(); System.out.println(s);

    and

  2. System.out.println(someObject.toString());

Looking at the generated bytecode, it seems to have differences. Is the JVM able to optimize this bytecode at runtime to have both solutions providing same performances ?

In this simple case, of course solution 2 seems more appropriate but sometimes I would prefer solution 1 for readability purposes and I just want to be sure to not introduce performances "decreases" in critical code sections.

Thanks in advance

Manu

A: 

Compared to output to the console, I doubt that any difference in performance between the two is going to be measurable. Don't optimize before you have measured and confirmed that you have a problem.

jerryjvl
A: 

If you have critical code sections that demand performance, avoid using System.out.println(). There is more overhead incurred by going to standard output than there ever will be with a variable assignment.

Do solution 1.

Edit: or solution 2

Kekoa
+2  A: 

There is no* code critical enough that the difference between your two samples makes any difference at all. I encourage you to test this; run both a few million times, and record the time taken.

Pick the more readable and maintainable form.

* Exaggerating for effect. If you have code critical enough, you've studied it to learn this.

Michael Petrotta
+1  A: 

The generated bytecode is not a good measure of the the performance of an given piece of code, since this bytecode will get analysed, optimised and ( in case of the server compiler ) re-analysed and re-optimised if it is deemed to be a performance bottleneck.

When in doubt, use a profiler.

Robert Munteanu
+1 for "use a profiler"
C. Ross
+4  A: 

The creation of a temporary variable (especially something as small as a String) is inconsequential to the speed of your code, so you should stop worrying about this.

Try measuring the actual time spent in this part of your code and I bet you'll find there's no performance difference at all. The time it takes to call toString() and print out the result takes far longer than the time it takes to store a temporary value, and I don't think you'll find a measurable difference here at all.

Even if the bytecode looks different here, it's because javac is naive and your JIT Compiler does the heavy lifting for you. If this code really matters for speed, then it will be executed many, many times, and your JIT will select it for compilation to native code. It is highly likely that both of these compile to the same native code.

Finally, why are you calling System.out.println() in performance-critical code? If anything here is going to kill your performance, that will.

tgamblin
Thanks for the answer. The println was just here for example (and I must admit was a poor Example). Of course I am not using it in critical code sections.Manu
Manuel Selva