Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In Java, if I am building a significant number of strings, is there any difference in performance in the following two examples?

StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {


StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {


share|improve this question

closed as off topic by gnat, Yusubov, Walter, StuperUser, Ryathal Nov 2 '12 at 19:45

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 4 down vote accepted

There is no performance difference between the two styles.

StringBuilder returns itself from all append operations making this easy (for some) to make it clear that you are still working on the same object.

The first style is more traditional and preferred by some groups as a code style.

The second style is known as method chaining. This is a style that is preferred by groups who prefer a fluent interface. Also give Martin Fowler's article on the fluent interface a read.

Key thing to read there is the word "preferred" and "style". Which one you use is up to you and your group.

share|improve this answer
Perfect answer.. – JAVA Jul 17 '13 at 15:22

There is no difference in performance.

That said, first option is better because second one is what code stylists call a train wreck.

Read this article on train wrecks

share|improve this answer
It does not violate the Law of Demeter. The Law of Demeter is not "only one dot". Each append returns back the string builder. You can operate on that object without violating LoD. – user40980 Nov 2 '12 at 15:53
it does not violate the law of demeter… – jk. Nov 2 '12 at 15:53
@MichaelT True. Corrected. – Tulains Córdova Nov 2 '12 at 15:55
So... why would this be considered a trainwreck? – user40980 Nov 2 '12 at 16:28
@user1598390 the example given in the article has each working on another object further down in the hierarchy of the object. That would rightly be called a train wreck waiting to happen. However, having a method do(foo) { ...; return this; } and then would not fall into what is described in the article. – user40980 Nov 2 '12 at 16:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.