Search code examples
javaif-statementhashmap

What is more efficient? An If Else or a HashMap?


I'm writing some code in Java to check in which quadrant a coordinate is and I was wondering which method is more efficient to check this: a if-else block or the use of a HashMap.

A HashMap would look like this:

private static final Map<Coordinate,Quadrant> quadMap = new HashMap<Coordinate, Quadrant>(){{
    put(new Coordinate(0,0), Quadrant.Q1);
    put(new Coordinate(0, 1), Quadrant.Q2);
    put(new Coordinate(1, 0), Quadrant.Q3);
    put(new Coordinate(1, 1), Quadrant.Q4);
}};

And then where I want to get my quadrant:

return quadMap.get(coordinate)

The if-else implementation:

if (x < 1){
        if (y < 1){
            return Quadrant.Q1;
        } else {
            return Quadrant.Q2;
        }
    } else {
        if (y < 1){
            return Quadrant.Q3;
        } else {
            return Quadrant.Q4;
        }
    }

Or is there another, more efficient way to do this?


Solution

  • For just four entries? The if-else will be faster. The hashmap has to do more commands to get you there. Fetch hashcode, calculate distance/position, fetch the array entry, and run an equals operation.