Java代码效率,存储数据与方法调用

JME*_*JME 1 java performance jvm

我对java中的代码效率有疑问.我目前有一个类似于以下方法

public class Response extends SuperResponse {

private Object ConfigureResponse = null;

public String getId() {
    if(this.getBody() == null || this.getBody().isEmpty()) {
        return null;
    } else {
        // Check if the ConfigureResponse has already been deserialized
        // if it has, there is no need to deserialize is again

        if(ConfigureResponse == null) {
            ConfigureResponse = JAXB.unmarshal(new StringReader(
                    this.getBody()), Object.class);
        }
        return ConfigureResponse.getConfigureResponse().getId();
    }
}
}// End class
Run Code Online (Sandbox Code Playgroud)

如果重复调用该getId方法,最好保存Id字符串并直接返回,并保存自己的方法调用以返回它吗?或者Java编译器是否足够智能以直接转换这些方法调用.

Ada*_*ion 6

编译器无法进行此类优化,但JVM随着时间的推移能够强烈优化此类方法,但前提是它们经常被调用.这显然需要时间,因此如果:

  • 从该方法调用的getId方法非常耗时
  • 什么是至关重要的,你确定 它们是你的应用程序的性能瓶颈,因为"过早的优化是所有邪恶的根源"

那么最好引入getId结果的缓存,可以通过以下方式实现: