efficient way to compare multiple int values to 0

Wylandylan123 :

I'm trying to compare three lengths to 0 and was wondering if there was a more efficient/cleaner way than repeating "!= 0".

public static boolean isTriangle(int lengthA, int lengthB, int lengthC) {
    if (lengthA != 0 && lengthB != 0 && lengthC != 0) { //is there a shorter/cleaner way to write this?
        //do a thing
    }
    return false;
}
Erwin Bolwidt :

You're asking three things; you're asking for code that is

  1. shorter
  2. more efficient
  3. cleaner

I have an alternative for you:

if ((lengthA & lengthB & lengthC) != 0)

It's correct - it does the same as your old code (it uses bitwise-and)

  1. it is shorter.
  2. it's potentially more efficient but only a good microbenchmark can confirm. Even if it is, that shouldn't guide you. Because of point 3, you should only consider it if it shows up as a bottleneck in your app using a performance analyzer tool, which is very, very unlikely.
  3. however it's not cleaner. And with that I mean that it will make your code harder to read and understand, and anyone maintaining your code will now have to think about bit manipulation.

Most likely the same will go for any proposed alternative.

What you were doing in your original code is good enough; it's what people understand, and it's most likely the cleanest code you can write for the purpose.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310076&siteId=1