Search code examples
javaoptimizationcoordinatesword-wrap

Which is faster: a conditional or a few extra arithmetic operations?


This is one of those tiny optimization questions that doesn't matter, but is fun to think about anyway.

I've got two different lines of Java code I could use:

  1. coord < 0 ? (coord % max + max) % max : coord % max or
  2. (coord % max + max) % max

I assume max is always a positive int and coord could be any valid int. I believe these two lines should always yield the same result, which is to wrap a coordinate that's gone off the edge of my map where there be monsters.

2 is clearly faster in the case that coord is negative. But if coord is positive, I'm not sure which would tend to be faster. The point of 1 would be to do less math operations in the case that coord is positive but I'm not sure if that's actually faster or not. The compiler might even optimize 1 away into being 2. Does anyone know?

By the way, I've seen people online post functions for wrapping coordinates which just add max in the case that coord is negative, and that breaks in the case that coord > max*-1. I want mine to deal with that case.

(later edit) The context is up on Github for anyone who would like to see it. And yes, I know this doesn't actually matter to the performance of my program, but I just thought it was an interesting question.


Solution

  • You're using a too complicated expression for the negative case:

    coord < 0 ? (coord % max + max) % max : coord % max
    

    is the same as

    coord < 0 ? coord % max + max : coord % max
    

    A mispredicted branch can be costly, however on modern i86/amd64, branching can be eliminated using a conditional move. So the condition is most probably faster.

    Note that guava uses it, too.