优化:访问字段与方法
我知道优化的第一条规则是:不要这样做!但我认为这是一个简单的问题,如果我现在开始使用更快的方法,当我完成时我可以节省大量的 cpu 时间。
我正在制作一个角色扮演游戏,假设这是自定义类的一部分:
public class Baddie{
int health;
int magic;
public Baddie(int health, int magic){
this.health = health;
this.magic = magic;
}
public int getHealth(){
return health;
}
现在,我的问题的答案可能是“没有区别”,这对我来说很好......我只是想知道。使用现场访问来获取坏人的健康状况是否更快:
//Somewhere in the main thread, I get an instance of Baddie..
Baddie b = getScaryBadGuy();
int baddieHealth = b.health;
还是使用返回方法更快?
int baddieHealth = b.getHealth();
I know rule #1 of optimization is: don't do it! But I figured this was an easy question, and if I start using the faster method now I can save a lot of cpu time when I'm finished.
I'm making an RPG, and let's say this is part of a custom class:
public class Baddie{
int health;
int magic;
public Baddie(int health, int magic){
this.health = health;
this.magic = magic;
}
public int getHealth(){
return health;
}
Now, the answer to my question may be "there's no difference" and that's fine with me.. I just want to know. Is it quicker to get the Baddie's health using field access:
//Somewhere in the main thread, I get an instance of Baddie..
Baddie b = getScaryBadGuy();
int baddieHealth = b.health;
Or is it quicker to use a return method?
int baddieHealth = b.getHealth();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从性能设计复制并粘贴:
Copied and pasted from Designing for Performance:
性能总是相对的。通常最好用百分比或因子来思考。如果某件事需要一微秒,也许这就是很多,也可能什么都不是。这取决于您每秒需要执行多少次。这就是过早优化不受欢迎的主要原因,它是在不知道是否存在问题的情况下完成的。
Performance is always relative. It's usually better to think in terms of percentages or factors. If something takes a microsecond, maybe that's a lot, and maybe it's nothing. It depends on how many times per second you need to do it. That's the main reason premature optimization is frowned upon, it is done without knowing if there is a problem.
如果可以的话,编译器会进行优化。这是过早优化的一个完美例子。使用代码中任何有意义的内容。不用担心“节省周期”。任何其他操作所需的数百万个周期都超过了这可能会节省或可能不会节省的 2-3 个周期。
The compiler will optimize if it can. This is a perfect example of premature optimization. use whatever makes sense in your code. Don't worry about "saving cycles". The 2-3 cycles this may or may not save is outweighed by the millions of cycles it takes for any other operation.
在我看来,这更多的是一个设计问题而不是优化问题。我建议不要编写/生成任何 getter 或 setter,直到您确实需要从类外部访问它们。这往往会保持尽可能低的耦合。
或者,默认情况下将这些 getter/setter 设为私有会产生相同的结果,但代码更多,但没有真正的好处。
IMO it's more a design question than optimization question. I would suggest not writing/generating any getter or setter until you actually need them to be accessed from outside of your class. This tends to keep coupling as low as possible.
Alternatively making those getters/setters private by default would have the same result but it's more code for no real benefit.