简体   繁体   中英

Access static fields directly instead of calling a static getter method, is it faster?

I'm writing an Android app and I have a class that generates and maintains some fixed URL's that can occasionally change. I keep them all in one class called 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;
   }
}

I have to make a lot of calls to getUrlBase() above, so I was thinking about making sUrlBase public and access it directly. Will this approach be better in terms of performance?

Yes, for performance reasons you should avoid use of getters and setters. Here is a tip from android " Designing for performance " doc.

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.

If you are not going to change your url more frequently, then instead of getter/setter method I will say that you can keep static directly

public static String google_url = "http://google.com";
public static String yahoo_url  = "http://yahoo.com";

In keeping static method, it may happen that due to some problem static setter values are removed (reset to original). So, in that case it will return you the original constant of static value.

UPDATE:

If your are going to update your URL dynamically then static method would prove to be better option.

    public static String sUrlBase = "http://google.com"; 

    public static String getsUrlBase() {
        return sUrlBase;
    }
    public static void setsUrlBase(String sUrlBase) {
        this.sUrlBase = sUrlBase;
    }

It makes no difference. You should use whatever method is easiest for you. Usually you should use getters and setters for readability and code practices.

Normally I would not worry too much about performance for small simple data like URL as in this case, and so for that matter whether it is direct field access or access using methods will not bother me much. The case where it will makes difference for me is when frequency of getter calls is so high that it is affecting overall response. My concern will be regarding changing the value accidentally [bugs :( ] since the field has public static access. When accessed through getter/setter at least there is one place where I can do some checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM