views:

62

answers:

1

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;
    }
}
+3  A: 

b = a; will have higher performance, since it's just assigning a reference. b.append is 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 a and b are both local variables, so if you do b = a, you can use b until the end of the method. However, it will not affect the caller.

In contrast, b.append modifies the object in-place. No new object is created, so this mutation is visible outside the method.

Matthew Flaschen
@Matthew: I did not get `In contrast, b.append modifies the object in-place. No new object is created, so this mutation is visible outside the method` . It's still a local variable right ? So it cannot be referenced outside the scope of the callee and hence would not be visible
darkie15
@darkie15: The StringBuilders are created outside of the method and passed in. So the outside will see what happens to them (in the append case).
Thilo
@Thilo: Aahh got it. Missed out the parameters.
darkie15