Check if variable null before assign to null?

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

    This will make your code so much harder to read that even if it was an optimization it wouldn't be worth the trouble.

    And it's not an optimization. On most modern cpu's if statements are quite expensive.

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

    This is actually (very, very slightly) less efficient. Variable assignments are roughly equivalent to null checks, plus there's an extra branch possible. Not that it makes much difference.

    Or is this worrying about nothing?

    You got it.

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

    This is a micro-micro-optimization (and possibly something handled by the compiler anyways). Don't worry about it. You'll get a far greater return by focusing on your programs actual algorithm.

    We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. -- Donald Knuth

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

    This will have little or no effect. I don't think you could even create a benchmark to demonstrate the difference.

    In fact, some would argue that assigning to null at all is a code smell (see the PMD detector for NullAssignment):

    Assigning a "null" to a variable (outside of its declaration) is usually bad form. Some times, the assignment is an indication that the programmer doesn't completely understand what is going on in the code. NOTE: This sort of assignment may in rare cases be useful to encourage garbage collection. If that's what you're using it for, by all means, disregard this rule :-)

    In general, I'm personally leery of anything that attempts to encourage garbage collection (you almost always get effects that you didn't expect).

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

    If you have a decent compiler they will generate identical code. If you have a crappy compiler the one with the if will be worse. On 2009 hardware assignments to variables are very cheap, and conditional branches can sometimes be expensive.

    0 讨论(0)
  • 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).

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