非淡泊无以明志,非宁静无以致远。非学无以广才,非志无以成学。

Map-HashMap 与 IF 判断内存占用对比

HashMap与IF判断内存占用对比,事实证明,Map对象在以下情况确实比IF判断占用内存低。

HashMap占用内存:13000

package com.taiping.bky;

import java.util.HashMap;
import java.util.Map;

public class test {
    public static void main(String[] args) throws Exception {
        long start = 0;
        long end = 0;
        // 先垃圾回收
        System.gc();
        start = Runtime.getRuntime().freeMemory();
        int seatCount = 2; // 需要进行判断的变量
        String projectCode;// 判断之后赋值的变量
        String type = "A";
        Map<Integer, String> map = new HashMap<Integer, String>();

        if (type.equals("A")) {
            map.put(2, "0001");
            map.put(4, "0002");
            map.put(5, "0003");
            map.put(6, "0004");
            map.put(7, "0005");
        } else {
            map.put(2, "0006");
            map.put(4, "0007");
            map.put(5, "0008");
            map.put(6, "0009");
            map.put(7, "0010");
        }
        projectCode = map.get(seatCount);// 采用map的get方式取值
        // 快要计算的时,再清理一次
        System.gc();
        end = Runtime.getRuntime().freeMemory();
        System.out.println("一个HashMap对象占内存:" + (end - start));
    }
}

 IF判断占用内存:18376

package com.taiping.bky;

import java.util.HashMap;
import java.util.Map;

public class test {
    public static void main(String[] args) throws Exception {
        long start = 0;
        long end = 0;
        // 先垃圾回收
        System.gc();
        start = Runtime.getRuntime().freeMemory();
        int seatCount = 2; // 需要进行判断的变量

        String projectCode;// 判断之后赋值的变量

        String type = "A";

        /** 优化之前,逻辑判断太多,效率低下 */
        if (type.equals("A")) {
            if (seatCount == 2) {
                projectCode = "0001";
            } else if (seatCount == 4) {
                projectCode = "0002";
            } else if (seatCount == 5) {
                projectCode = "0003";
            } else if (seatCount == 6) {
                projectCode = "0004";
            } else if (seatCount == 7) {
                projectCode = "0005";
            }
        } else {
            if (seatCount == 2) {
                projectCode = "0006";
            } else if (seatCount == 4) {
                projectCode = "0007";
            } else if (seatCount == 5) {
                projectCode = "0008";
            } else if (seatCount == 6) {
                projectCode = "0008";
            } else if (seatCount == 7) {
                projectCode = "0010";
            }
        }
        // 快要计算的时,再清理一次
        System.gc();
        end = Runtime.getRuntime().freeMemory();
        System.out.println("一个IF判断占内存:" + (end - start));
    }
}

 

posted @ 2019-12-03 11:02  Happy丶小鱼  阅读(1098)  评论(0编辑  收藏  举报