0

I implemented following example code to reduce memory and time complexity of creating new complex object. It works faster than initial duplicates method in both complexities. My implementation is like follows:

public class ComplexObject{
    //set of heavy maps and lists
    public ComplexObject(int id, String param1, String param2){
        //init set of maps - this costs higher process time
    }
}
public class Test {
    Map<String,ComplexObject> complexObjectMap= new HashMap<>();
    public ComplexObject addObject(int id, String param1, String param2){
        if(complexObjectMap.containsKey(id + param1 + param2)){
            return complexObjectMap.get(id + param1 + param2);
        }
        else{
            ComplexObject complexObject = new ComplexObject(id, param1, param2);
            complexObjectMap.put(id+param1+param2,complexObject);
            return complexObject;
        }
    }
}

Can this be further optimized? in both complexities. Entirely different approach is also acceptable.

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
  • 1
    Depending on your data, it might be risky to simply concat the keys. There would be no way to distinguish between `(11, "11", "11")` and `(1, "11", "111")`. You can probably work around that with a safe delimiter, but it may be best to create a light holder POJO that implements `hashCode()` and `equals()` and use that as your key. – shmosel Mar 06 '20 at 03:30
  • 1
    data keys will not be overlapped according to the specification – Nilanka Manoj Mar 06 '20 at 03:33
  • 2
    Instead of `if(complexObjectMap.containsKey(id + param1 + param2)){` `return complexObjectMap.get(id + param1 + param2);` `}` you could probably simply have: `ComplexObject co = complexObjectMap.get(id + param1 + param2);` `if (co != null) return co;` to save one getNode call from the HashMap. But probably the compiler will optimize that for you anyway. – Michał Urbaniak Mar 06 '20 at 04:11

0 Answers0