Two ways to access android string resources

I am trying to understand the difference between accessing android resource strings. The following quote is not clear to me:

Referee access fast

Slow access

access by reference means: setTitle(R.string.title)

direct access means: setTitle(getResources().getString(R.string.title))

Now I ran some speed tests on an Android emulator:

access by link :

 for(int i = 0; i< 100000; i++) { setTitle(R.string.app_name); } 

It took 5090 milliseconds . In contrast, I run the same code using direct access :

 for(int i = 0; i< 100000; i++) { setTitle(getResources().getString(R.string.app_name)); } 

It took 5191 milliseconds . I tested this with Android 4.2.2.

So for me it looks a lot like it doesn’t matter how I use the resources. Was this in previous versions of Android? Does this apply to real devices? In other words: does it matter what access I choose?

If you need additional parameters for my testing, I am happy to provide them. Thanks for taking the time, really appreciate it.

+4
source share
1 answer

Just look at the code:

(In action)

 public void setTitle(int titleId) { setTitle(getText(titleId)); } 

(in the context)

 public final CharSequence getText(int resId) { return getResources().getText(resId); } 

So basically, this is exactly the same.

However, it is much slower if you use Resource.getIdentifier(String, String, String) to search for the identifiers of your resources.

+3
source

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


All Articles