• Post Reply Bookmark Topic Watch Topic
  • New Topic

Size of a String object - memory usage

 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Would the above code appropriately give the amount of heap memory being used by the StringBuffer 'sb'. The above code tells be that a String of 1000 characters occupies around 220Kbytes of memory. Is that all it would occupy?

I want to determine if I should initialize a huge String outside a loop and use it within a 1000-iteration loop. or if I should create the String within the loop and allow garbage collection to reclaim the String's memory after each iteration.

If the memory that that String would take is less than an MB, I should choose the former choice, I guess.

[ October 18, 2007: Message edited by: Sylvester James ]
[ October 18, 2007: Message edited by: Sylvester James ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Sylvester]: Would the above code appropriately give the amount of heap memory being used by the StringBuffer 'sb'.

No, not at all. You're adding up the values of each byte. In general a single character requires 2 bytes of memory*, and so a String of 1000 characters would require approximately 2000 bytes of memory, or slightly more (because a String object has more data than just the char[] array, but the char[] array is usually the largest part).

* This isn't really true for chars stores as individual variables, which may well use more memory, typically 4 or 8 bytes depending on whether you have a 32-bit system, or 64-bit. But it's generally true for chars in arrays, which use more space-efficient storage.

It's hard to answer your main question, because originally you were talking about StringBuffer, and now you're talking about Strings. Can you show some code that shows how you intend to use this String/StringBuffer/whatever?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!