Speed of custom Java classes vs. Maps

Tags: ,



Which is faster:

  1. a Set whose elements are each an instance of CustomObject as defined below:

    public class CustomObject{
    
        private static String A;
        private static String B;
        private static String C;
    
        public static String getA(){
            return A;
        }
    
        public static getB(){
            return B;
        }
    
        public static getC(){
            return C;
        }
    }
    
  2. a Set whose elements are each an instance of Map<String, String> where each Map is of the format {"A" : Avalue, "B" : Bvalue, "C" : Cvalue}?

  3. or any other data structure that you can think of that better captures this data

if I want to get a subset of all objects/maps who have the attribute/key A == “somevalue”?

You can use .filter, or any other libraries. Also, does the answer change if the set is large?

EDIT: I just had one of my coworkers tell me that the runtime of a custom class is faster than a hashmap– why would anyone ever use a hashmap, then?

Answer

I’m assuming that we are comparing Map<String, String> to the equivalent custom type like this:

public class CustomObject {
    private String a, b, c;

    public CustomObject(String a, String b, String c) {
        this.a = a; this.b = b; this.c = c;
    }
    public String getA() { return a; }
    public String getB() { return b; }
    public String getC() { return c; }
}

If the operations we are comparing are obj.getA() versus map.get("A"), then the custom map will be faster, probably by 1 to 2 orders of magnitude. Yes … a lot faster.

On the other hand, if we put the CustomObject instances into a set of “mixed type” objects, whose fields we don’t know anything about, then calling getA becomes much more difficult / expensive, and the Map solution is certainly simpler and possible faster too. (It depends on the assumptions you can make.)


Also, does the answer change if the set is large?

No. It doesn’t change the performance characteristics significantly.


Why would anyone ever use a hashmap, then?

The use-cases where it is better / necessary to use a Map are when the set of possible keys are not known at compile time. This means that you can’t write the CustomClass as a regular class with hand-written source code.

In fact, in most cases it is the relative code simplicity and robustness of the two approaches that should decide the approach you take. If the keys are static, the obj.getA() approach isn’t just faster. It is also more robust, because you can’t accidentally write something like map.get("a") instead of map.get("A") … which will return an unexpected null and could lead to an NPE. If the keys are dynamic / not known at compile time, the map.get("A") is simpler and probably more robust.



Source: stackoverflow