Results 1 to 3 of 3
Like Tree2Likes
  • 2 Post By eRaaaa

Thread: Best way to clear a StringBuilder.

  1. #1
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Saint Louis, Missouri
    Rep Power

    Default Best way to clear a StringBuilder.

    Hello all.

    I have a Java program I have written. I chose to use StringBuilder as there is a LOT of concatenation going on. Also since I don't know how big the StringBuilder will need to be I don't initialize it.

    My question is that at a certain point I need to clear the StringBuilder out. I have read the API and there are two ways I can do it:


    Java Code:
    StringBuilder sb = new StringBuilder();
    sb.setLength( 0 )
    sb.delete( 0, sb.length() );
    Both work, I would just like to know the most efficient way.

    If you aren't programming in Java, well that's just too bad.
    I'd rather be using Ubuntu.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Rep Power

    Default Re: Best way to clear a StringBuilder.

    Do you have performance issues? If not, why are you thinking about things like that now?

    (btw: a third way is to create a new one and the gc will do the rest :D)
    Fubarable and quad64bit like this.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Richmond, Virginia
    Blog Entries
    Rep Power

    Default Re: Best way to clear a StringBuilder.

    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"


    That isn't to say you shouldn't think about which is more optimal, but if the API documentation doesn't specify which you should use, it's safe to use whichever you like.

Similar Threads

  1. StringBuilder
    By Dayanand in forum New To Java
    Replies: 5
    Last Post: 03-04-2011, 08:31 AM
  2. StringBuilder
    By tmotse in forum New To Java
    Replies: 3
    Last Post: 09-13-2010, 08:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts