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?
A summary of its performance: TreeMap provides a performance of O(log(n)) for most operations like add(), remove() and contains() A Treemap can save memory (in comparison to HashMap) because it only uses the amount of memory needed to hold its items, unlike a HashMap which uses contiguous region of memory.
There is no standard small implementation of Map in Java. HashMap is one of the best and most flexible Map implementations around, and is hard to beat.
HashMap does not maintain any insertion order of its elements hence it is quicker than Map. In contrast to Map, HashMap can hold duplicate values. It's possible to implement the Map interface by utilizing its implementing classes.
Besides that, hashmaps are less space efficient than arrays because they always have a load factor which is smaller than one, which is the same as saying that they keep more entries allocated than necessary due to the way they work.
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.
What you are utilizing in your first example is called Double-Brace Initialization. It creates an anonymous class only for the purpose of laziness, which is extremely inefficient on multiple levels. Also, unless you cache it, a hashmap consumes a lot of memory and has a relatively slow initialization time. A simple if
is definitely more efficient here.
Generally, if-else will always be more efficient. But with a certain number of cases, you should use a (properly initialized) Map for the sake of readablity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With