Reputation: 4256
I am using fragments in my Android app. In these fragments I need a Context object for using it repeatedly (about 10 times) with some method calls.
As you know, I have 2 options:
OPTION I:
public class MyFragment extends Fragment{
public void onCreate(Bundle savedInstanceState){
super(savedInstanceState);
//call a lot of methods and use getActivity() a lot of times
}
}
OPTION II:
public class MyFragment extends Fragment{
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super(savedInstanceState);
mActivity = getActivity();
//call a lot of methods and use mActivity
}
}
I know that declaring mActivity field will require some memory ( how much? ), but I think calling getActivity will need some CPU processing.
Which of these 2 options is better and why?
EDIT:
Well, looking the Android source code I can find the source of getActivity() method inside Fragment class:
final public FragmentActivity getActivity() {
return mActivity;
}
So, as you can see, in the Option II mActivity is reserved twice, which is a waste of memory so from now I will use Option I.
Thanks for your answers, they made me understand about this :)
Upvotes: 6
Views: 501
Reputation: 4256
Well, looking the Android source code I can find the source of getActivity() method inside Fragment class:
final public FragmentActivity getActivity() {
return mActivity;
}
So, as you can see, in the Option II mActivity is reserved twice, which is a waste of memory so from now I will use Option I.
Thanks for your answers, they made me understand which about this :)
Upvotes: 3
Reputation: 18863
but I think calling getActivity will need some CPU processing.
It is less than you think. getActivity is just acessing a field, getting the Activity. it doesn't have much CPU involved. Your second method which will require a little heap of memory and first will require a little stack, see this for performance.
In the other hand. This is premature optimization. if you don't have any memory problems when current code.
Upvotes: 4
Reputation: 19278
The second option is better. You will only use getActivity() once. In the first option you will call it many times which is expensive. Declaring mActivity will ofcource cost some memory. Since mActivity is not really a object, but a reference to the object, it won't take that much memory.
Upvotes: 2