gpt4 book ai didi

java - 计算分配对象所需的内存

转载 作者:行者123 更新时间:2023-11-30 07:36:01 25 4
gpt4 key购买 nike

我想比较内存使用情况,分配 Calendar 对象和 Joda 的 DateTime 对象。

// 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 Joda TimeDate objects?
for (int i = 0; i < 100; i++) {
DateTime dateTime = new DateTime();
l = l + dateTime.getMillis();
DateTimeList.add(dateTime);
}

我可以知道是否可以添加任何代码来进行测量?

最佳答案

使用检测获取内存使用情况的提示:

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();
}
}

其他选项:MemoryMXBean但我从未使用过它。

关于java - 计算分配对象所需的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4043899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com