Which of these two options is best for performance?

I use fragments in my android app. In these fragments, I need a Context object to reuse it (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 the mActivity field will require some memory (how much?), But I think that calling processor getActivity will require some processing.

Which of these two options is better and why?


EDIT:

Well, looking at the Android source code, I can find the source of the getActivity () method inside the Fragment class:

 final public FragmentActivity getActivity() { return mActivity; } 

So, as you can see, in Option II, mActivity is reserved twice, which is a waste of memory, so now I will use Option I.

Thanks for your answers, they made me understand about it :)

+6
source share
3 answers

Well, looking at the Android source code, I can find the source of the getActivity () method inside the Fragment class:

 final public FragmentActivity getActivity() { return mActivity; } 

So, as you can see, in Option II, mActivity is reserved twice, which is a waste of memory, so now I will use Option I.

Thanks for your answers, they made me understand what about it :)

+3
source

but I think calling getActivity will require some processor processing.

It is less than you think. getActivity just captures the field, getting an Activity. it does not have a large number of processors involved. Your second method, which will require a small heap of memory and first, will require a small stack, see this for performance.

On the other hand. This is premature optimization. if you have no memory problems with the current code.

+4
source

The second option is better. You will use getActivity () only once. In the first option, you will call it many times, which is expensive. Recognizing mActivity will cost some memory. Since mActivity is not really an object, but a reference to an object, it does not take up so much memory.

+2
source

All Articles