Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of this 2 options is better for performance?

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 :)

like image 241
BamsBamx Avatar asked Dec 17 '13 23:12

BamsBamx


2 Answers

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.

like image 150
wtsang02 Avatar answered Sep 30 '22 13:09

wtsang02


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 :)

like image 32
BamsBamx Avatar answered Sep 30 '22 13:09

BamsBamx