gpt4 book ai didi

java - 如果最终确定,公共(public) getter 和 setter 是否适用于 Android? Java 中的最终正确性与 C++ 中的常量正确性一样重要吗?

转载 作者:行者123 更新时间:2023-11-30 11:31:25 27 4
gpt4 key购买 nike

<分区>

我正在读这个:http://developer.android.com/training/articles/perf-tips.html

特别是关于内部 getter 和 setter 的:

Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.

Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter.

它提到“虚拟方法调用”,可能也指公共(public)方法。我的类中有很多方法不应被覆盖。例如:

public class Something {
private float m_Float = 0.0f;
public float getFloat () {
return m_Float;
}
}

我总是希望“getFloat()”返回“m_Float”,即使在派生类中也是如此。将方法标记为“最终”是否会提高 Android 设备的性能?即使没有,最终正确性与常量正确性一样重要吗?比如,当同事忘记最终正确性时,Java 程序员会生气吗?

如果将方法标记为 final 可以提高性能,那么下面的性能增益是否会被抵消?

public class Base {
public int getRandomNumber () {
return 4; //chosen by fair dice roll.
//guaranteed to be random.
}
}
public class Derived extends Base {
public final int getRandomNumber () {
return 6; //chosen by second fair dice roll.
//guaranteed to be more random.
}
}

目前我对优化我的代码并不感兴趣,但我对最终正确性位感兴趣。我不熟悉 Java 所关注的标准约定。

[编辑]

好的,所以,上面给出了这个链接作为可能的答案:Android Performance - 'Avoid Internal Getters/Setters'

标记为答案链接的回复:What optimizations can I expect from Dalvik and the Android toolchain?

现在似乎内联了简单的 getter 和 setter。

In Gingerbread we added simple inlining for getters/setters. Since the underlying JIT frontend is still simple trace based, if the callee has branches in there it won't be inlined. But the inline cache mechanism is implemented so that virtual getters/setters can be inlined without problems.

在评论中,有人问:

(3) Should I declare my methods final wherever possible? Or does that still count as a virtual callsite?

这是回复:

(3) Yes please

所以,有了这里的评论等等,我想说一切都解决了。 (除了何时 final 应该与方法一起使用;但这可能很快就会得到回答。我有一个信念,但我正在等待它得到验证或有理由被驳斥,所以..)

[编辑]

此外,这是否意味着 Android 文档。关于性能提示是..过时了?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com