Check if variable null before assign to null?

后端 未结 8 1207
清歌不尽
清歌不尽 2021-01-05 16:55

Is variable assignment expensive compared to a null check? For example, is it worth checking that foo is not null before assigning it null?

if (foo != null)          


        
8条回答
  •  余生分开走
    2021-01-05 17:22

    
    foo = null;
    
    
    if (foo != null)
       foo = null;
    

    If I look at the second block code I would think that you only wanted to set the foo variable to null if it was not null before, and if I look at the first code I would think that you wanted to set the variable foo to null anyway.

    I know this is because of the example you wrote, but in the end this kind of micro-optimization only adds confusion (it's not worth it).

提交回复
热议问题