局部变量分配以避免多个强制转换 [英] Local variable assignment to avoid multiple casts
问题描述
最近有一个问题,询问是否在Java中将调用getter的结果分配给局部变量是为了避免对同一个访问器的多次调用。我找不到原始的帖子,但一致似乎是一般不是必要的,因为Hotspot会优化方法调用开销无论如何。
There was recently a question asking whether it was a good idea in Java to assign the results of calling a getter to a local variable to avoid multiple calls to the same accessor. I can't find the original post but the consensus seemed to be that this generally isn't necessary as Hotspot will optimise away the method call overhead anyway.
但是,是使用这种技术避免多次投掷的观点?目前我面临着一个选择:
However, what is the view on employing this technique to avoid multiple casts? At the moment I'm faced with a choice between:
if (a instanceof Foo) {
// Cast once and assign to local variable.
Foo foo = (Foo)a;
if (foo.getB() == 1 && foo.getC() == 2) {
...
}
}
或
if (a instanceof Foo) {
// Cast twice making code compact but possibly less readable.
// Also, is there an overhead in multiple casts?
if (((Foo)a).getB() == 1 && ((Foo)a).getC() == 2) {
...
}
}
推荐答案
除了删除演员表,这也意味着你可以获得使用不同的名称 - 毕竟,你现在知道更多关于这个变量,所以它可能是有意义的,给它一个更具体的名称。这不总是这样,但它可以。 为了命名一个值,引入局部变量重构技术是一个低估的,即使没有施放... ...
In addition to removing the casts, it also means you get to use a different name - after all, you now know more about this variable, so it may well make sense to give it a more specific name. That's not always the case, but it can be. The "introduce local variable for the sake of naming a value" refactoring technique is an underappreciated one, even without the casts...
这篇关于局部变量分配以避免多个强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!