代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

计算分配对象所需的内存

  •  2
  • Cheok Yan Cheng  · 技术社区  · 15 年前

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

    我能知道我能加上什么代码来衡量吗?

    3 回复  |  直到 15 年前
        1
  •  2
  •   user85421    15 年前

    使用检测获取内存使用提示:

    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 但我从没用过。

        2
  •  2
  •   InsertNickHere    15 年前

    Java visual vm 工具,在那里你可以看到什么对象占用了什么内存。我认为没有一个“代码内”的解决方案在所有情况下都是正确的,只需要几行代码。

        3
  •  0
  •   pgras    15 年前

    你可以看看下面的 Java Specialists' newsletter