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
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    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:

    Example:

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

    Thanks.
    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
    Location
    Germany
    Posts
    787
    Rep Power
    6

    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
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    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"

    -Knuth

    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, 09:31 AM
  2. StringBuilder
    By tmotse in forum New To Java
    Replies: 3
    Last Post: 09-13-2010, 09: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
  •