Java Optimizations

前端 未结 5 1769
忘了有多久
忘了有多久 2021-01-24 04:38

I am wondering if there is any performance differences between

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

    and

  2. System.out.pr

5条回答
  •  心在旅途
    2021-01-24 05:20

    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.

提交回复
热议问题