I have a StringBuilder a. I have to append a‘s content to StringBuilder b. If b is null, then assign b=a, otherwise b.append(a.toString()).
Is there any performance difference on checking if the StringBuilder is null or not?
method_a(StringBuilder a, StringBuilder b) {
if (b != null) {
b.append(a.toString();
} else {
b=a;
}
}
b = a;will have higher performance, since it’s just assigning a reference.b.appendis a method call, and requires copying characters, and (potentially) creating a new character array.The question is whether that’s what you want. Note that
aandbare both local variables, so if you dob = a, you can usebuntil the end of the method. However, it will not affect the caller.In contrast,
b.appendmodifies the object in-place. No new object is created, so this mutation is visible outside the method.