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 :)
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With