Which is more efficient? “If something” or “Hash card”?

I am writing Java code to check which quadrant has a coordinate, and I was wondering which method is more efficient to check: if-else block or using HashMap.

HashMap will 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) 

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?

+5
source share
5 answers

Only four entries? If-else will be faster. A hashmap needs to do more teams to get you there. Fetch hashcode, computes the distance / position, retrieves the array entry and starts the equality operation.

+8
source

What you use in the first example is called Double Binding Initialization . It creates an anonymous class just for laziness, which is extremely inefficient at several levels. In addition, if you do not cache it, the hash card consumes a lot of memory and has a relatively slow initialization time. A simple if definitely more efficient here.

As a rule, if-else will always be more efficient. But with a certain number of cases, you should use a (properly initialized) card for readability.

+3
source

It depends on how many coordinates you have. If you have a very small number, then if if else will be slightly faster than calculating the hash and finding it. If you only ever have 4 coordinates, it is more likely to use if / else faster than using a HashMap.

+1
source

Most likely, HashMap , but it depends on a couple of things:

  • the Coordinate class must have an efficient implementation of equals() and hashCode()
  • whether the Coordinate immutable and the hash code can be cached
  • what coordinates you go through.
0
source

All these answers are based on the difference between if-else and hashmap, but from the point of view of the algorithm, your if-else will work more optimally, and you do not need all this space in the hash map. Whenever you get a coordinate, if you pass it through an if-else, then you will get a response, and thus you do not need to use a map, and you can save memory. Make an if block utility function for ease of use anywhere in your program.

0
source

Source: https://habr.com/ru/post/1215351/


All Articles