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编译器是否足够智能以直接转换这些方法调用.
编译器无法进行此类优化,但JVM随着时间的推移能够强烈优化此类方法,但前提是它们经常被调用.这显然需要时间,因此如果:
getId方法非常耗时那么最好引入getId结果的缓存,可以通过以下方式实现:
向该类添加新属性Response:
private String id;
Run Code Online (Sandbox Code Playgroud)将getId方法重命名为populateId
getId使用这样的代码创建一个新方法:
public String getId() {
if (this.id != null) {
return this.id;
}
this.id = populateId();
return this.id;
}
Run Code Online (Sandbox Code Playgroud)