• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does string immutability not come at cost of taking more memory?

 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings are immutable but does it not add to it taking more memory.(Despite the concept of string pooling).
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64718
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How did you come to that conclusion?
 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since strings are unchangeable everytime new String has to be created(Unless it is in the pool).Thus despite the pooling concept one ends up creating new objects each time and thus taking memory.

thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64718
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ignoring the string pool, any unused string are garbage collected.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are certain things you should not do with strings, because they are immutable. For example, repeatedly adding to a string in a loop is bad:

When you do this, in each iteration of the loop, a new String object is created into which the content of the previous String object is copied, with the extra "yip" appended.

Instead of doing this, you should use StringBuilder, which is essentially a mutable String object:

So, there are certainly situations where you have to be aware what happens with your strings, and you'd better use a StringBuilder instead.
 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic