Issue
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?
Solution
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.
Answered By - laalto
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.