Java优化 [英] Java Optimizations

查看:97
本文介绍了Java优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何性能差异

I am wondering if there is any performance differences between


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

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

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

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

查看生成的字节码,它似乎有差异。 JVM是否能够在运行时优化这个字节码以使两个解决方案都提供相同的性能?

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 ?

在这个简单的情况下,当然解决方案2似乎更合适但有时候我更喜欢解决方案1用于可读性目的,我只是想确保不在关键代码部分中引入性能减少。

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.

推荐答案

创建一个临时变量(特别是像String一样小的东西)对代码的速度无关紧要,所以你应该不再担心这个。

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.

尝试测量实际值在这部分代码中花费的时间,我打赌你会发现根本没有性能差异。调用 toString()所花费的时间并打印出结果需要的时间远远超过存储临时值所需的时间,我认为你不会在这里找到一个可衡量的差异。

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.

即使字节码在这里看起来不同,也是因为 javac 是天真的,你的JIT编译器为你做了繁重的工作。如果这段代码真的对速度很重要,那么它将被执行很多次,你的JIT会选择它来编译为本机代码。很可能这两个编译为相同的本机代码。

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.

最后,为什么要调用 System.out.println()在性能关键代码中?如果这里的任何事情会破坏你的表现,那就会。

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

这篇关于Java优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆