I'm trying to understand what the best practice is and why for concatenating string literals and variables for different cases. For instance, if I have code like this
StringBuilder sb = new StringBuilder("AAAAAAAAAAAAA")
.append(B_String).append("CCCCCCCCCCC").append(D_String)
.append("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE")
.append("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
Is this the way to do it? From this post, I noticed that the +
operator on Strings creates a new instance of StringBuilder, concatenates the operands, and returns a String conversion, which seems like a lot more work than just calling .append()
; so if that's true, then that is out of the question. But what about String.concat()
? Is it proper to use .append()
for every concatenation? Or just for variables, and literals are okay to append with .concat()
?
StringBuilder sb = new StringBuilder("AAAAAAAAAAAAA")
.append(B_String.concat("CCCCCCCCCCC")).append(D_String
.concat("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE")
.concat("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"));
What are the general rules for best practices and performance for going about these situations? Is my assumption correct on +
and it should really just not be used?