Is accessing static fields directly rather than calling a static getter method faster?

I am writing an Android application, and I have a class that generates and maintains some fixed url that can change from time to time. 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 need to make a lot of calls to getUrlBase() above, so I was thinking about making sUrlBase public and access it directly. Would this approach be better in terms of performance?

+4
source share
4 answers

If you are not going to change your URL more often, then instead of the getter/setter method I will say that you can save static directly

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

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

UPDATE:

If you are going to update your URL dynamically , then a static method will be the best option.

  public static String sUrlBase = "http://google.com"; public static String getsUrlBase() { return sUrlBase; } public static void setsUrlBase(String sUrlBase) { this.sUrlBase = sUrlBase; } 
+2
source

Yes, for performance reasons, you should avoid using getters and setters. Here is the advice from android " Design for Performance " doc.

Without JIT, direct access to the field is about 3 times faster than calling a trivial getter. With JIT (where direct access to a field is cheaper than access to a local one), direct access to fields is about 7 times faster than causing a trivial getter. This is true in Froyo, but will improve in the future when JIT uses getter methods.

+5
source

It does not matter. You must use any method for you. You should usually use getters and setters for easier reading and code usage.

0
source

Normally, I wouldn’t worry too much about performance for small simple data such as a URL, as in this case, and therefore, whether direct access to the field or access using methods, I don’t really bother. The case when it will matter to me is when the frequency of getter calls is so high that it affects the overall response. My concern will be to change the value randomly [bugs :(], since the field has static access open. When accessing via getter / setter there is at least one place where I can do some checks.

0
source

Source: https://habr.com/ru/post/1396827/


All Articles