开发者

Is just setting a value faster than the checking of existance and only setting if doesn't exist - like in this Android / Java code?

开发者 https://www.devze.com 2023-01-21 16:28 出处:网络
Example: That code is run each time, when the listAdapter requests a new row: if (textViewTitle != null)

Example:

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

if (textViewTitle != null)
          textViewTitle.setTypeface(Controller.getInstance().widgetSettings.getBoldTy开发者_运维百科peface());

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消