Given an existing code base being used in production containing a class A that contains a method that populates N fields of another POJO class B using setters and returns the POJO to the caller and given that all instances of class B will be different in regards to only two field i.e, N - 2 fields will be the same across all instances of class B, would there be any performance gain if class A has a static reference to class B and initializes the fields of class B that don't change in a static init block? This way, the method in class A that was populating N fields of class B on each call will now have to populate only two fields which are different. This will also eliminate the need to create a new object of type B for each call to the method in class A. What are the implications of this approach in a multi-threaded application?
Alternately, we can declare all the fields in class B that don't change as static so that the method in class A only sets the fields that change per call. Either ways, will the performance gain be worth it or this change qualifies as premature optimization?
Example :
class A {
private static B b = new B();
static {
b.setSystem("MySystem");
b.setVersion("1.1");
}
public B getB(String name) {
b.setName(name);
return B;
}
}