我有一个关于 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
在重复调用 getId
方法的情况下,保存 Id 字符串并直接返回该方法是否会更好,并节省我自己的方法调用以返回它?或者 Java 编译器是否足够智能,可以直接转换这些方法调用。
最佳答案
编译器无法进行此类优化,但随着时间的推移,JVM 能够强烈优化此类方法,但前提是它们被频繁调用。这显然需要时间,因此如果:
- 从
getId
方法调用的方法真的很耗时而且 - 这里最重要的是,您确定它们是您应用程序的性能瓶颈,因为“过早的优化是万恶之源”
那么最好引入getId
结果的缓存,可以通过以下方式实现:
向类
Response
添加一个新属性:private String id;
将
getId
方法重命名为populateId
使用这样的代码创建一个新的
getId
方法:public String getId() { if (this.id != null) { return this.id; } this.id = populateId(); return this.id; }
关于Java 代码效率,存储数据与方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739405/