9

if (a == 0 && b == 0) {}

or

if (a + b == 0) {}

What do you think is more readable? Is there any (performance) difference in the compiled programme?

For a and b >= 0.

Comments
  • 20
    a=-1, b=1

    Have you thought about it?

    Update: now you have
  • 2
    @ruhe No, I forgot. Thanks for mentioning! I added a restriction to the post.
  • 1
    @zlice Indeed, the second one has one compare less than the first one, but therefor an addition that the first one hasn't.

    And even with more variables, for every less comparation there will be an addition in assembly.
  • 3
    more readable you say?
    I'd go with this:

    if(!(a-b!=0 || a>0)) {}
  • 0
    Complete condition is different. What if a==-b?
  • 1
    I assume the top one is quicker because the second check will not be done if the first one fails.
  • 3
    Wow it is really rare to see a dev who cares about performance at this extent, very good.

    if(a==0 && b==0) will take 3 cycles at worst, 2 at best ( where a is 0, it will skip b==0 part but still gonna JMP anyways )

    if(a+b==0) would take 1 cycle, but poor readability since an outsider wouldn't realize natural number guaranteed parameters right away.

    if(a&&b) Sounds good, doesn't work. Plus poor readability. 1 cycle but pass.

    I would go for first option, since it doesn't require any comment to explain what is going on. I think most of the time, 2 extra cycles won't hurt much.
  • 0
    How are you forcing a,b >=0 ? Unsigned ints I assume?

    a = 0xffffffff
    b = 1

    a+b forces an overflow back to zero
Add Comment