Java中的过早优化:何时使用“x = foo.getX()” vs简单地说“foo.getX()” [英] Premature optimization in Java: when to use "x = foo.getX()" vs simply "foo.getX()"
问题描述
当我发现自己多次调用相同的getter方法时,这应该被视为一个问题吗? [总是]分配给局部变量并且只调用一次会更好吗?
When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?
我确定答案当然是它取决于。
I'm sure the answer of course is "it depends".
我更关心的是更简单的情况,即getter只是一个传递私有变量值类型的方法。即没有涉及昂贵的计算,没有消耗数据库连接等等。
I'm more concerned about the simpler case where the getter is simply a "pass-along-the-value-of-a-private-variable" type method. i.e. there's no expensive computation involved, no database connections being consumed, etc.
我的它是否更好的问题涉及代码可读性(样式)和性能。即具有如此大的性能影响:
My question of "is it better" pertains to both code readability (style) and also performance. i.e. is it that much of a performance hit to have:
SomeMethod1(a, b, foo.getX(), c);
SomeMethod2(b, foo.getX(), c);
SomeMethod3(foo.getX());
vs:
X x = foo.getX();
SomeMethod1(a, b, x, c);
SomeMethod2(b, x, c);
SomeMethod3(x);
我意识到这个问题有点挑剔和灰色。但我刚才意识到,我根本没有一致的方法来评估这些权衡。钓鱼的标准不仅仅是完全异想天开。
I realize this question is a bit nit-picky and gray. But I just realized, I have no consistent way of evaluating these trade-offs, at all. Am fishing for some criteria that are more than just completely whimsical.
谢谢。
推荐答案
选择不应该是关于性能损失而是关于代码可读性。
The choice shouldn't really be about performance hit but about code readability.
当你创建一个变量时,你可以给它一个它应得的名字。目前的背景。当你多次使用相同的值时,它肯定具有真正的意义,而不仅仅是方法名称(或者更糟糕的方法链)。
这真的更好看:
When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
And it's really better to read:
String username = user.getName();
SomeMethod1(a, b, username, c);
SomeMethod2(b, username, c);
SomeMethod3(username);
比
SomeMethod1(a, b, user.getName(), c);
SomeMethod2(b, user.getName(), c);
SomeMethod3(user.getName());
这篇关于Java中的过早优化:何时使用“x = foo.getX()” vs简单地说“foo.getX()”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!