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.