The pattern in the 2nd example is a "fluent API" / "fluent interface"; frankly neither is strictly better - but if the second exists it can be slightly inefficient not to use it. In .NET IL terms, the first syntax involves an extra ldloc
and pop
per iteration, which the second avoids - but that is rarely hugely significant. Either will work fine.
Personally, I would optimize for readability and convenience unless you know it is in a performance-critical spot.
Indeed, you could just use:
string s = "Have a " + "nice day!";
which the compiler (in C#, at least - I don't know about java) will compute at compile-time (since they are both constants) and compile down to a single ldstr
(which is automatically interned, too).
StringBuilder
's API (otherwise it just seems arbitrary if only some methods allow chaining). – Jon Feb 25 '13 at 9:14