zoukankan      html  css  js  c++  java
  • 计算一个对象所占内存大小

    主要思路 就是先获取当前占用内存(usedMemory) 然后创建对象 再获取当前占用内存 两次内存差就是该对象所占内存大小   runGC()方法提供垃圾回收在每次获取内存前可以先调用 

    private static final Runtime s_runtime = Runtime.getRuntime();

     private static void runGC() throws Exception {
      // It helps to call Runtime.gc()// using several method calls:
      for (int r = 0; r < 4; ++r)
       _runGC();
     }
     private static void _runGC() throws Exception {
      long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
      for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
       s_runtime.runFinalization();
       s_runtime.gc();
       Thread.currentThread().yield();
       usedMem2 = usedMem1;
       usedMem1 = usedMemory();
       }
      }
     private static long usedMemory() {
      return s_runtime.totalMemory() - s_runtime.freeMemory();
     }
     

    路漫漫其修远兮,吾将上下而求索
  • 相关阅读:
    2.5 整数和算法
    斑马问题
    计算机硬件操作
    幸福是什么
    英译汉技巧
    指令
    计算机性能
    硬盘容量的计算方法
    Symmetric Tree
    Same Tree
  • 原文地址:https://www.cnblogs.com/IT-WJ/p/3610847.html
Copyright © 2011-2022 走看看