Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Memory size and access  RSS feed

 
Steve Chambers
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a data structure that is basically hashmaps of hashmaps. The keys of the hashmaps are strings and the values are are objects that contain data.

Is there a way to see how much memory this is taking up?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could get a rough idea from the memory related methods in java.lang.Runtime - print out the value of freeMemory() before and after the construction of the data structure. Thats assuming all the Strings and data objects exist before building the hashmaps.

Look at the source code for whichever collection you are using to see what structures are built. It can be quite instructive.

Bill
 
Shawn Vader
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way of getting an accurate size is to Serialize the HashMap as it is Serializable and you say they contain Strings which are also serializable
and then look at the size OutputStream. I have found this to be the most accurate way of finding out the size of an object

Sun as a good article http://java.sun.com/developer/technicalArticles/Programming/serialization/

Or if you have the time Effective Java by Joshua Bloch has a fantastic chapter on Serialization http://java.sun.com/docs/books/effective/

Shawn
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The number of bytes used for the serialized form of an object isn't generally the same as the number of bytes used in memory. For example, Strings usually take two bytes per character (plus a little extra) in memory, but the serialized form uses UTF-8 which takes only one byte per character if the chars are ASCII. You'll get more accurate measurements with totalMemory() and freeMemory(), if the size of the objects is large and if there's been good thorough garbage collection before each measurement. (E.g. I would run System.gc() ten times in a row.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!