0

Looking for the best (?) way to replace contents of a StringBuilder

I normally use this

StringBuilder stringBuilder = new StringBuilder("abc");

stringBuilder.setLength(0);
stringBuilder.append("12");

I guess one could also point to a new StringBuilder

StringBuilder stringBuilder = new StringBuilder("abc");

stringBuilder = new StringBuilder("12");
2
  • 3
    What are your criteria for "best"? What's the context here? Do you know how long the next final string will be? Commented May 1, 2013 at 19:28
  • 1
    So basically you want to "reset" the StringBuilder? I tend to find that just creating a new one is the most clear way to do it. Commented May 1, 2013 at 19:32

1 Answer 1

3

Reusing a StringBuilder like this usually saves you little to nothing. Personally, I would never bother with these things; just create a new StringBuilder object, it's simple, consistent (you're not resetting your POJO's, right?).

So, I'd say, keep it simple, and go for the second option, unless you've got some interesting constraints not mentioned in your initial post.

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

2 Comments

What about if you pass the StringBuilder as param in a method and you need to receive the manipulated StringBuilder back? For example: doMethod(stringBuilder); In this case if you use new StringBuilder("12") in the doMethod, then the caller method will not get the update. Right?
Well, set aside that this would be a horrible way of programming (simple rule: never manipulate your input, please read Clean Code), you are right; in that case you'd have to return the new StringBuilder instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.