views:

66

answers:

4

In data structures, I know that the size of the structure depends on the internal links from one section to another. Is there a way, aside from JProfiler to tell exactly how much memory is tied up in a particular structure?

For example, the class project this semester has to do with applying various structures to a song database. The projects have covered arrays, lists, unrolled lists and trees. What I would like to do is see how much memory is used. For example, a linked list has a memory requirement of 3N, but I would like to see how much space a node is taking up in my project.

JProfiler looks like it would work, but $500 is out of my price range, and I would like to use it for all the structures covered this semester, not the three applied so far.

+2  A: 

alt text

Use VisualVM. It comes with the JDK and allows you to take a snapshot of the heap.

Amir Afghani
Thanks, this looks like what I was looking for.
Jason
@Amir Afghani I believe you left a word or two off the end of your
Lawrence Johnston
It looks like I did LOL thanks. Fixing
Amir Afghani
A: 

Use System.getRuntime().freeMemory().

Run the garbage collector; Check the free memory; create one of your objects; check the free memory; subtract.

novalis
Based on how garbage collection works, there is no guarantee that this will produce a valid amount for the size of an object. Not to say it won't, just that there is an ever present possibility that it will give you some value that is wrong.
phill
Sure, there's no guarantee, but I've never heard of it failing in practice. Have you?
novalis
+1  A: 

Most accurate way is probably to use a profiler - use Google to find free ones.

Alternatively, you can try the technique in Do you know your data size?.

Yevgeniy Brikman
+1  A: 

I have honestly never used this before, but there is a getObjectSize method as part of Instrumentation interface which may be able to provide the answers you want without a third party application. It may not be easier then VisualVM, as Amir suggested, but it never hurts to read about it.

phill