Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLayoutInflater vs LayoutInflater.from

Tags:

android

Studying some (known to be good) code I can see the logic as follows:

if (getContext() instanceof Activity) {
      inflater=((Activity)getContext()).getLayoutInflater();
}
    else {
      inflater=LayoutInflater.from(getContext());
}

I wonder, why this if/else, how it is better to, just, using LayoutInflater.from in all cases?

like image 898
Alexander Kulyakhtin Avatar asked Oct 30 '14 07:10

Alexander Kulyakhtin


1 Answers

It doesn't really matter much.

Activity delegates getLayouInflater() to Window. The usual policy implementation of Window PhoneWindow in turn initializes its inflater with LayoutInflater.from(context) where context is the activity.

So the inflater object is really the same, using the same Context in case of an activity.

LayoutInflater.from() is really a wrapper for Context.getSystemService(). Now, system services are looked up by name from a map and then retrieved from a cache. This lookup has some overhead when compared to accessing an already initialized member variable in Activity.

So it smells like a micro optimization that does not likely affect much runtime performance when compared to actual view hierarchy inflation.

This optimization can actually have negative impact on developer productivity as people need to stop and spend some thinking why the code is there.

like image 58
laalto Avatar answered Sep 21 '22 17:09

laalto