gpt4 book ai didi

java - 直接访问静态字段而不是调用静态getter方法,是不是更快?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:55 26 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序,我有一个类可以生成和维护一些偶尔会更改的固定 URL。我将它们全部保存在一个名为 UrlUtils 的类中:

public class UrlUtils {
private static String sUrlBase = "http://google.com";

/**
* Called occasionally
*/
public static void refreshUrlBases() {
sUrlBase = "http://yahoo.com/" + new Random().nextInt();
}

public static String getUrlBase() {
return sUrlBase;
}
}

我必须对上面的 getUrlBase() 进行大量调用,所以我在考虑将 sUrlBase 公开并直接访问它。这种方法在性能方面会更好吗?

最佳答案

是的,出于性能原因,您应该避免使用 getter 和 setter。这是来自 android“Designing for performance”文档的提示。

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. This is true in Froyo, but will improve in the future when the JIT inlines getter methods.

关于java - 直接访问静态字段而不是调用静态getter方法,是不是更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9310776/

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