javaperformancegetter-setterbuilder-pattern

About performance of builder pattern


In order to have tested more readable and easy to write I usually use the BuilderPattern in my value object. For example instead of writing this simple class in a standard way:

public class MyClass{

    private String myProperty;

    public void setMyProperty(String myProperty){
       this.myProperty = myProperty;
    }
}

I prefer to write it as follows:

public class MyClass{

    private String myProperty;

    public MyClass setMyProperty(String myProperty){
       this.myProperty = myProperty;
       return this;
    }
}

Could this approach has a bad effect on performance?


Solution

  • Your code snippet is not about using the builder pattern (GoF/Bloch) it is only about using fluent mutators or chain setters. A common practice with no really performance impact.

    Regarding builder you have the additional Builder-object. But directly elligible for garbage collection after the creation of the object.

    So you may have some impact on memory-usage. But JVM is really optimized to handle this.