Check if variable null before assign to null?

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

提交回复
热议问题