Question of the Week No. 107
September 29, 2000
Researched by Ramchander Varadarajan
Question of the Week presents answers to key questions posed by the
developer community. The intent is to pass this important, but not
always easy-to-find, information on to Java Developer ConnectionSM (JDC) members. The
questions are selected from the JDC
Forums
generally because: they are frequently asked, they are significant or timely,
or
the answers are not easily accessible.
Topic:
Calculating Memory Used by Objects
Question:
How can I calculate number of bytes occupied by an object in memory? I have a object as follows:
public class obj {
private String str = new String("ABCDE");
private int i;
}
If I create ten objects of Obj
class, how much memory space do they occupy?
Answer:
The Runtime.totalMemory()
method should help. However, because memory is being allocated and deallocated all the time, you should probably create a lot of the
same objects and then divide the change in memory by the number of objects.
class MemoryTest {
protected static final long COUNT = 100;
public static void main(String[] arg) {
long start, end, difference;
Object[] array = new Object[COUNT];
long i;
Runtime.getRuntime.gc(); // let's hope the
// garbage collector runs
start = Runtime.getRuntime().totalMemory();
for (i = 0; i < COUNT; i++) {
array[i] = new Object();
}
Runtime.getRuntime.gc();
end = Runtime.getRuntime().totalMemory();
difference = (end - start) / COUNT;
System.out.println("Approximately " + difference
+ " bytes used by 1 java.lang.Object with
default constructor");
}
}
WARNING: Strings are optimized to use as little memory as possible by reusing the same object if the strings are the same. You're going to have to do something
special to test these out:
1. Make a program to write a bunch of random, same-length strings to a file (Let's say "strings.txt").
2. Use the code given above.
3. Before you calculate the start, open "strings.txt" with a FileReader
or input stream.
4. In the for loop, read the a string from the file and put it in the array.
5. Close the file after the second call to the totalMemory()
method.
If you use this code in any other form, don't declare or construct any objects between the calls to the totalMemory()
methods. This could alter results.
For more information:
Class Runtime
Many thanks to JDC member cakoose for contributing to this answer.
Note: If you have a question to which you need an answer, try the JDC Forums. You can read through
the existing topics, or with your
free JDC membership, you can post
new messages or threads.
Submit your comments or answers to this question here!