Is just setting a value faster than the checking of existance and only setting if doesn’t exist – like in this Android / Java code? – Education Career Blog

Example:

That code is run each time, when the listAdapter requests a new row:

if (textViewTitle != null)
          textViewTitle.setTypeface(Controller.getInstance().widgetSettings.getBoldTypeface());

vs.

if (textViewTitle != null 
    && textViewTitle.getTypeface() != null
    && textViewTitle.getTypeface().equals(Controller.getInstance().widgetSettings.getBoldTypeface()))
          textViewTitle.setTypeface(Controller.getInstance().widgetSettings.getBoldTypeface());

,

It depends entirely on how costly the creation and equality operation are. It should be trivial to benchmark as needed if performance is that important.

If performance isn’t so important, then the former is far more readable, and conveys just as much information about the intention of the code as the latter.

,

Make sure textViewTitle always refers to something so you don’t need to check for its existence.

,

Maybe setTypeface is more than just setting a property, for example causes redrawing? In this case you would like to avoid calling it unless it changes something.
BTW in second code if original typeface is not set, it won’t be set. I’m not sure if it’s intended.

Leave a Comment