Compute memory required to allocated objects
I would like to compare memory usage, to allocate Calendar object and Joda's DateTime object.
// How much memory required to allocate 100 Calendar objects?
for (int i = 0; i < 100; i++) {
Calendar c = Calendar.getInstance();
l = l + c.getTimeInMillis();
CalendarList.add(c);
}
// How much memory required to allocate开发者_StackOverflow中文版 Joda TimeDate objects?
for (int i = 0; i < 100; i++) {
DateTime dateTime = new DateTime();
l = l + dateTime.getMillis();
DateTimeList.add(dateTime);
}
May I know is there any code I can add in to measure?
Use instrumentation to get an hint of memory usage:
public class MemUsage {
public static void main(String[] args) {
Instrumentation instr = InstrumentationAgent.getInstrumentation();
if (instr == null) {
System.err.println("No Instrumentation, use the VM option \"-javaagent:Instrumentation.jar\"");
return;
}
System.out.println();
System.out.println("an implementation-specific approximation of the amount of storage");
System.out.println("Calendar = " + instr.getObjectSize(Calendar.getInstance()));
System.out.println();
}
}
Other option: MemoryMXBean but I never used that.
You could use the Java visual vm tool, there you can see what objects take what memory. I don't think there is a "in code" solution that is correct in all cases with a few lines of code.
You may have a look at the following Java Specialists' newsletter
精彩评论