简体   繁体   English

设置一个值是否比检查存在性和仅设置不存在(例如在此Android / Java代码中)要快?

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

Example: 例:

That code is run each time, when the listAdapter requests a new row: 每次在listAdapter请求新行时,都运行该代码:

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. 如果性能不是那么重要,那么前者的可读性要高得多,并且传达的信息与后者一样多。

确保textViewTitle始终引用某些内容,因此您无需检查其是否存在。

Maybe setTypeface is more than just setting a property, for example causes redrawing? 也许setTypeface不仅仅是设置属性,例如导致重绘? 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. 我不确定这是否有意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM