I am working on one project for performance enhancement. I had one doubt, while we are during a process, we tend to trace the current state of the DTO and entity used. So, for this we have included toString() method in all POJOs for the same. I have now implemented toString() in three different ways which are following :-
public String toString() {
return "POJO :" + this.class.getName() + " RollNo :" + this.rollNo + " Name :" + this.name;
}
public String toString() {
StringBuffer buff = new StringBuffer("POJO :").append(this.class.getName()).append(" RollNo :").append(this.rollNo).append(" Name :").append(this.name);
return buff.toString();
}
public String toString() {
StringBuilder builder = new StringBuilder("POJO :").append(this.class.getName()).append(" RollNo :").append(this.rollNo).append(" Name :").append(this.name);
return builder .toString();
}
can anyone please help me to find out which one is best and should be used for enhancing performance.
The one with the
+is fine in this case. It’s more readable, and it’s just as performant compared to theStringBuilder/StringBufferversion, since it’ doesn’t happen inside a loop.If you are building a
Stringinside a loop, then more often than not you should useStringBuilder. Only useStringBufferif you need itssynchronizedfeature, which doesn’t happen very often.Simplistically speaking (not true always, but is a good rule of thumb), unless you’re doing a
+=with aString, you don’t really need aStringBuilder/StringBuffer.Related questions
A
String.formatoptionOne option often not considered is to use
String.format. It’ll look something like this:I find that this is the most readable and maintainable version.
Is this faster? Maybe yes, maybe not. It usually doesn’t matter for common use case scenarios for something like
toString(). Strive for readability, only optimize if profiling says it’s necessary.API links
java.util.FormattersyntaxOn Class Literals
I’ve corrected a syntax error in the original code from
this.class(which doesn’t compile) tothis.getClass().See also
Related questions