Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Views: can checking visibility before setting visibility improve performance?

Tags:

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?

like image 820
Steven Byle Avatar asked Mar 01 '13 18:03

Steven Byle


1 Answers

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.

like image 71
Geobits Avatar answered Oct 20 '22 12:10

Geobits