Which of this 2 options is better for performance?

Viewed 490

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

3 Answers
Related