24

I have helper methods that set the visibility of certain Views depending on the state variables that are passed into the methods. Sometimes, these methods will get called many times and the Views visibility will not change. So I found myself starting to check the visibility of each View before setting it with the thinking, "No point in changing a View's visibility to the same visibility and causing a refresh for no reason".

            if (myView.getVisibility() != View.VISIBLE) {
                myView.setVisibility(View.VISIBLE);
            }
            etc...

However, now I'm wondering if the implementation of setVisibility already takes this into account, and checks if you are setting the same visibility to what the View already has, and doesn't needlessly refresh the View (what my code is trying to do).

So does anyone know if my "optimization" is actually improving any performance, or is the API already a step ahead of me?

Steven Byle
  • 13,149
  • 4
  • 45
  • 57
  • yes, you are improving the performance, because you dont tell the VM to load `setVisibility` every time. – Mohammad Ersan Mar 01 '13 at 19:05
  • @Geobits actually as you said, setting the visibility will not refresh the view if the visibility is the same, but if he is asking for code performance in his case this will improve. – Mohammad Ersan Mar 01 '13 at 19:12
  • but `setVisibilty` will call another methods:1- `setFlags` , 2- `mBackground.setVisible` – Mohammad Ersan Mar 01 '13 at 19:15
  • and all these methods will be loaded even they will not work. – Mohammad Ersan Mar 01 '13 at 19:17
  • 1
    I was more concerned with not refreshing the `View`, the method calls to check the visibility are negligible (in the scope I'm looking to improve on). I just wanted to make sure I wasn't making a check that was already happening (which I now know is). Thanks for the help guys. – Steven Byle Mar 01 '13 at 19:18

1 Answers1

52

They're already one step ahead. See the code for View.java:setVisibility():

public void setVisibility(int visibility) {
    setFlags(visibility, VISIBILITY_MASK);
    ...
}

It calls setFlags():

void setFlags(int flags, int mask) {
    int old = mViewFlags;
    mViewFlags = (mViewFlags & ~mask) | (flags & mask);

    int changed = mViewFlags ^ old;
    if (changed == 0) {
        return;
    }
    ....
} 

It checks to see if the flag matches the current state. If so, it simply returns without doing anything.

Geobits
  • 22,218
  • 6
  • 59
  • 103