Check if variable null before assign to null?

后端 未结 8 1089
清歌不尽
清歌不尽 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:25

    I wouldn't worry about it - it's just extra lines of code to maintain. This is the sort of micro-optimization you should never do unless you have lots of documented proof that it's your bottleneck.

    0 讨论(0)
  • 2021-01-05 17:30

    First of all, it's micro optimization. So no need to worry much about it.

    But to answer your question, you need to reduce it to just one line. (as all your code does is to set it to NULL).

    foo = NULL;
    

    Reasons being that,

    Comparison is a much much costlier operation than assignment. (As comparison eats up many assembly instructions comparatively. Generally a subtraction and a comparison to zero or an XOR and comparison to zero). Assignment takes up fewer instructions.

    0 讨论(0)
提交回复
热议问题