Can casting to fragment be more efficient than using a variable? I'm new to using fragments in Android. I'm working on an app using a sliding panel layout and I just came up with an idea for changing my fragments. I decided to create the following method:

    private void changeFrag(Object newFrag){
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
        .replace(R.id.fragment_secondpane, (Fragment) newFrag).commit();
    }


I'm calling the method in the following way:

    changeFrag(new myFragment());


Could this cause problems for me in the long run? I was hoping that by writing it this way, I could avoid extra code and hopefully cut down on any extra processing power the device would need for something like this:

        Fragment frag;
        frag= new myFragment();

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
        .replace(R.id.fragment_secondpane, (Fragment) frag).commit();
You could make it more dynamic. Because this method adds the Fragment only to the R.id.fragment_secondpane layout. If this is all what you desire, it's ok. Otherwise add a parameter for the layout. This way you can use your method to add a Fragment to different layouts.

Because every type of Fragment like ListFragment, DialogFragment or even a SherlockFragment is using Fragment as super class, you can use Fragment as the parameter type. There's no need to use Object. Note that you should avoid to mix the Fragment types of different librarys.

With methods like this you can avoid extra code in this situation, replacing different Fragments of a specific layout. 

The processing will be the same. The creation of the necessary objects have to be done. There will be no difference if this happens in e.g. onCreate or the method you wrote. The only thing you could avoid is to hold an extra reference of the FragmentManager.

To sum all up you would have something like this:

private void changeFrag(int layout, Fragment newFrag){

    getSupportFragmentManager() // gets the FragmentManager of the Activity, no need to hold a reference
         .beginTransaction()
         .replace(layout, newFrag) // use the layout and the fragment, no need for a cast
         .commit();

}


Note that this method will work and is straightforward. If you have an approach with adding some Fragments to the backstack and some not or using different kind of animations, your method will be more complex and lacks performance. That's why I would not use this in every situation.