wood burning stoves*
The moose likes Java in General and the fly likes Value of using StringBuffer for this example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Value of using StringBuffer for this example" Watch "Value of using StringBuffer for this example" New topic
Author

Value of using StringBuffer for this example

Jared Cope
Ranch Hand

Joined: Aug 18, 2004
Posts: 243
Hi,

I appreciate that we should use StringBuffer (or StringBuilder) when possible in order to keep the String literal pool as small as possible. But I am wondering if all that good work is undone when the toString() method is called on a StringBuffer. For example:



does the toString call force creation of the String in the pool? Especially if the caller of this method does something like:



Any thoughts?

Thanks, Jared.


SCJP 1.4 91%, SCJP 1.5 88%, SCJD B&S
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3168
    
  10
Calling StringBuffer.toString() will not create anything in the String literal pool. That only contains references to String literals. It will however create a new String object on the heap.
In your example there is no advantage to using a StringBuffer. It could just be written asThis would be better because no StringBuffer object is created.


Joanne
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Yes that's right. Anyways the String literal "Test String" gets an entry in String Literal Pool


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes - but only one entry, no matter how many times the code is called. The idea that we need to "keep the string literal pool as small as possible" really is not necessary in the vast majority of applications. (Unless maybe you're using String.intern() an awful lot for some reason.) It really isn't something Jared needs to worry about.


"I'm not back." - Bill Harding, Twister
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

That's correct Jim. The same was suggested by Joanne Neal as well.


The idea that we need to "keep the string literal pool as small as possible" really is not necessary in the vast majority of applications. (Unless maybe you're using String.intern() an awful lot for some reason.)


But String's intern() method would intern ensures that the # of string literals are being referred to that of from the String Literal Pool right? But will it increase the entries or what?

And why is it not necessary in the majority of applications Jim? Of course it seems to be a matter of concern right?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Raghavan]: The same was suggested by Joanne Neal as well.

Some concepts I mentioned were repeated, yes. Others were new. Occasionally a fact gets repeated while putting new information in context. So what?

[Raghavan]: But String's intern() method would intern ensures that the # of string literals are being referred to that of from the String Literal Pool right?

I can't really tell what you're saying here. String literals already refer to strings in the string pool - there's no need of intern() for this.

[Raghavan]: But will it increase the entries or what?

Not usually. String literals cause strings to be stored in the pool regardless of whether intern() is used. But the intern() method can also cause additional, non-literal, strings to be stored in the pool. That will increase the number of entries in the pool. If you do this a lot, you may create a problem. But usually it's not.

[Raghavan]: And why is it not necessary in the majority of applications Jim? Of course it seems to be a matter of concern right?

No, it's not (except rarely). I have no idea where "of course" comes from there. You may be concerned about it, but the concern is not warranted.

Why is because:
  • In most programs, the number is string literals is much smaller than the amount of available memory.
  • Most programs do not use intern() at all. (Why should they?)
  • The programs that do use intern() generally do not use it too much. In some cases they can save memory by using intern(). Typically people don't bother using intern() unless they know what they're doing, so misuse of intern() is uncommon.
  • Memory is cheap. Many programs have more memory than they need anyway.

  • Now if you're programming in Java Micro Edition, you may be more likely to run out of memory. In this case you might need to pay more attention to how many literals you're using, and be careful about using intern(). But most programmers aren't using Java ME.
    Raghavan Muthu
    Ranch Hand

    Joined: Apr 20, 2006
    Posts: 3344

    Jim, thanks for the detailed reply as usual!

    Originally posted by Jim Yingst:

    Some concepts I mentioned were repeated, yes. Others were new. Occasionally a fact gets repeated while putting new information in context. So what?



    Yes, i dint oppose ! It was just to say that "Joanne was also suggesting the same, rather he was also in the list of people uttering the same fact"! Might be the coining of words would have given a different opinion i believe!


    I can't really tell what you're saying here. String literals already refer to strings in the string pool - there's no need of intern() for this.


    Yes, the same i also was intended to say!


    Not usually. String literals cause strings to be stored in the pool regardless of whether intern() is used. But the intern() method can also cause additional, non-literal, strings to be stored in the pool. That will increase the number of entries in the pool. If you do this a lot, you may create a problem. But usually it's not.


    Well, thanks for the additional information Jim.


    No, it's not (except rarely). I have no idea where "of course" comes from there. You may be concerned about it, but the concern is not warranted.

    ...But most programmers aren't using Java ME.


    Thats great and i am not aware of Java ME. But i got your point.

    Thank you Jim!
    Jhakda Velu
    Ranch Hand

    Joined: Feb 26, 2008
    Posts: 166
    Hi All
    Continuing the discussion, I just want to know how best it would be to use the String object. I highlight 2 scenarios


    Scene2


    I believe,if there are lot of append operations, its better to use the StringBuffer way rather than the String option. Why?
    Because

    leads to lot of String objects getting created.

    Am i thinking correctly?(use StringBuffer when lot of append operations are to be done, String otherwise) I'm a bit confused.

    Jhakda


    If I become filthy rich, I'll sponsor research for painless dental treatment at Harvard Medical School. Thats why,I'm learning Java.I have 32 teeth, 22 are man made.
    Piyush Porwal
    Ranch Hand

    Joined: Apr 09, 2008
    Posts: 30
    I agree. If you have lot of manipulations on the string, better is to use StringBuffer. Each manipulation on String object is actually creating string literals which are of no use after the required (say append/+) operation.

    Similar discussion


    -Piyush Porwal (Junk box)
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 36478
        
      16
    Agree: if you write

    it is far more efficient to writeBut there is a special case when everything is in one statement.

    If you writethere is an optimisation which calls a StringBuilder behind the scenes (at least in the more recent versions of Java), so in that latter case there is no difference.
    Jim Yingst
    Wanderer
    Sheriff

    Joined: Jan 30, 2000
    Posts: 18671
    [Jhakda]: Am i thinking correctly?

    In general, yes. However in the specific examples you've given, all the strings you're adding together seem to be literals. In this case, there is no reason not to use + to concatenate them - the whole expression will be evaluated as a single constant expression, and there will be no StringBuilder involved at all:

    This is effectively the same as:

    On the other hand if at least one part of the expression had been a variable, it would be different:

    This is equivalent to:

    Even here, there's no real reason to abandon the + operator. There will be a StringBuilder created either way, but the end effect is the same, and the code using + is cleaner to look at.

    The real benefit of using StringBuilder is when you cannot put the whole expression into a single line, or (especially) when the code is inside a loop that needs to append new data to previous data. That's because in those situations, it's much more effective to reuse an existing StringBuilder than to create a new one and copy the preexisting data into it.

    This is equivalent to

    It's much better to do this instead:

    These all have the same end result for s, but the last involves much less creation of new objects, and much less copying of existing data into those new objects. For a loop of just 10 iteration, the effect is minor. But if you loop 100 or 1000 times, the effect becomes very substantial.
    Jhakda Velu
    Ranch Hand

    Joined: Feb 26, 2008
    Posts: 166
    Hi
    Thanks everybody
    Understood now.

    Jhakda
    Raghavan Muthu
    Ranch Hand

    Joined: Apr 20, 2006
    Posts: 3344

    That's a wonderful explanation. Thank you Jim
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Jim Yingst:

    Now if you're programming in Java Micro Edition, you may be more likely to run out of memory.


    Why would using String.intern() make it more likely to run out of memory than not using it? I would expect the opposite...


    The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
    Jim Yingst
    Wanderer
    Sheriff

    Joined: Jan 30, 2000
    Posts: 18671
    I meant that you're more likely to run out of memory in general, and so you might need to be careful about any program that requires you to have many strings in memory simultaneously. You're right that using intern() isn't a problem itself, as far as I know, since the string pool by itself does not seem to prevent garbage collection.
    [ April 27, 2008: Message edited by: Jim Yingst ]
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Value of using StringBuffer for this example
     
    Similar Threads
    synchronization issue
    Puzzling String
    Concatenation of Strings using String vs. StringBuffer
    Stings: how many objects created?
    Again String.