zoukankan      html  css  js  c++  java
  • 对《java程序员上班那点事》笔者对数组占用内存质疑

    1.《java程序员上班那点事》笔者对数组占用内存的描述


    2.实际测试情况:


        /**
         * 测试一维数组占用内存
         */
        public static void testOneArray() {
            System.out.println("当前虚拟机的最大内存:" + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m------" + Runtime.getRuntime().maxMemory() + "byte");
            System.out.println("循环前虚拟机已占内存:" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m====" + Runtime.getRuntime().totalMemory() + "byte");
            try {
                int len = 1024 * 1024 * 300;// 设定循环次数
                byte[] buffer = new byte[len];
                for (int i = 0; i < len; i++) {
                    buffer[i] = (byte) i;
                }
                System.out.println("循环前虚拟机已占内存:" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m====" + Runtime.getRuntime().totalMemory() + "byte");
            } catch (Error e) {
                System.out.println("遇到错误:" + e);
            }
            /*
             * 测试结果:
               当前虚拟机的最大内存:793m------832438272byte 
               循环前虚拟机已占内存:127m====133234688byte 
               循环前虚拟机已占内存:427m====447877120byte
             */
        }
    
        /**
         * 测试二维数组占用内存
         */
        public static void testTowArray() {
            System.out.println("当前虚拟机的最大内存:" + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m------" + Runtime.getRuntime().maxMemory() + "byte");
            System.out.println("循环前虚拟机已占内存:" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m====" + Runtime.getRuntime().totalMemory() + "byte");
            try {
                int len = 1024 * 1024;// 设定循环次数
                byte[][] buffer = new byte[len][300];
                for (int i = 0; i < len; i++) {
                    buffer[i][0] = (byte) i;
                    buffer[i][1] = (byte) i;
                }
                System.out.println("循环前虚拟机已占内存:" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m====" + Runtime.getRuntime().totalMemory() + "byte");
            } catch (Error e) {
                System.out.println("遇到错误:" + e);
            }
            /*
             * 测试结果:
               当前虚拟机的最大内存:793m------832438272byte
              循环前虚拟机已占内存:127m====133234688byte
              循环前虚拟机已占内存:398m====417398784byte
             */
    }

    分析:个人认为,上面前辈的测试没有在循环直接输出以下jvm已占用的内存;对比我这次的测试,如果用循环之后的减去循环之前的占用的内存推翻了那位前辈的理论,正好相反,对于哪一种是正确的,有待大家的考证?!

  • 相关阅读:
    UITableview
    UIscrollview
    UITextField(详细设置)
    iOS开发UI篇—Quartz2D使用(矩阵操作)
    iOS开发UI篇—Quartz2D使用(图形上下文栈)
    类的sizeof
    Implement strStr()
    KMP很清楚的一篇解释
    Best Time to Buy and Sell Stock II
    Triangle
  • 原文地址:https://www.cnblogs.com/yangkai-cn/p/4016691.html
Copyright © 2011-2022 走看看