1

I would just like to ask if this is a good way of clearing/emptying a StringBuilder? It is wrapped in a method and it is called several times, is this thread safe? Does this not consume a lot of memory? Would it be better if I created the StringBuilder outside of the method and in the class instead?

private void callMe(){
    StringBuilder builder = new StringBuilder();
    builder.delete(0, builder.length());
}

builder.append("some ID");

if (builder.toString().contains("some other ID"))
    Show("Information")
else
    Show("Invalid ID")
Hiroga Katageri
  • 1,345
  • 3
  • 21
  • 40

2 Answers2

3

It would be more efficient to call

sb.setLength(0);

Because that's only one method call, instead of two.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Before I post my answer I am assuming that you are using StringBuilder in a loop and every few iterations you may want to empty it and start with an empty StringBuilder. In that case I can think of two approaches:

  • invoke setLength(0) on the string builder you are using. I prefer this over delete as I feel this is more neat.
  • Or allocate a new one instead rather than clearing the buffer. It may not be an ideal option but still an option.
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95