0

We are constructing a large block of text and are using a single instance of StringBuilder. We have broken up the block of text into subsections (5) and assigned each a corresponding method. Each method takes input variables and spits out text.

Is it better to pass in the StringBuilder object to each method, append the data in the method and return void or have each method return a string that we append to the object outside of smaller functions?

What would be some benefits/drawbacks to both ideas.

1
  • just an addition to the answers, you could try to guess how large the string would be and use StringBuilder(int capacity) to avoid resize overhead. Also why not use a templating engine ? Commented Apr 9, 2013 at 19:40

3 Answers 3

4

I'd pass in the StringBuilder, and append directly to it - assuming you don't actually need that intermediate string for any other reason.

The whole point of using StringBuilder is to avoid creating more strings than you need.

The main advantage of just returning strings is that if you ever want to use the same code in a situation where you're not appending to a StringBuilder, it's more convenient and idiomatic. But I'm assuming these are actually private methods just called from the "build the text" method, which makes it less of an issue.

Zim-Zam's point about parallelism is an interesting one, but I wouldn't worry about that unless you're actually planning to parallelize this.

Sign up to request clarification or add additional context in comments.

2 Comments

I also wonder if it would easier to generate cleaner unit tests. My first instinct was to have the subset functions spit out a string since I gravitate to generic reusable code, but the memory issue is also a valid point.
@user1500053: If you're unit testing these methods, does that mean they're not private?
1

Passing in a StringBuilder is more memory efficient because there's no need to garbage-collect the strings that are being appended. Returning strings is more amenable to parallelization because the strings can be generated concurrently and then appended in sequence.

Comments

1

fixed literal will be detected by compiler so here string is better to use

String s1="str1"+"str2"+"str3"; 

When you need to append strings dynamically, prefer StringBuilder

String s1=""; s1+="str1"; s1+="str2"; s1+="str3"; 

and use methods of StringBuilder to append and finally convert to toString();

as by using + to append later (compiler optimization is not done) more objects are created

So use StringBilder

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.