I have a pathfinding algorithm which is run many times and must be extremely efficient, so I’m wondering what I can do to boost performance. I have an if statement which says this:
if (!(n != 1 && map.isCornerObstructed(p)) {
// Do stuff...
}
It seems to me that the double inversion would take slightly longer than this logically equivalent version:
if (n == 1 || !map.isCornerObstructed(p)) {
// Do stuff...
}
The problem is that the former is more readable in the context of the code, so I’m somewhat reluctant to change it if I don’t know what the result will be.
Is one more efficient than the other? Or is the Java compiler smart enough to optimize things like this automatically?
The code
generates bytecode
The code
generates bytecode
which is exactly the same. Therefore, there will be no performance difference at all, no matter how finely you measure it. The compiled code is identical.
(Note that the reason for this is that
javacactually goes and decomposes theifstatement into individual condition tests and branches, so it actually works out the pathway for each possibility.)