HashMap的clear()操作和new HashMap的时间效率比较

来源:互联网 发布:mysql install db 编辑:程序博客网 时间:2024/04/29 08:54

结论:看来分配内存都很耗时啊,也是用clear()比较快

import java.util.*;/*在一个smallCostBigFunction()中就需要一个preRoud的clear操作, * 其中preRoud是全局变量,之所以用到全局变量,是因为smallCostBigFunction(),要将这个结果返回给dofire(), * 但它同时要给一个Cost给dofire(); * 这样大概进行的clear操作次数是 迭代次数+1 * preRoud<Integer,ArrayList>,clear的内部是for循环实现,每个preRoud设有500个key,每个key中存有包含有5个数据的ArrayList*/public class HashMapClear {    public static void main(String[] args) {        // TODO Auto-generated method stub        int iter=500;        HashMap<Integer,ArrayList> h=new HashMap<Integer,ArrayList>();        //clear        long sum=0;        for(int i=0;i<iter;i++)        {            for(int j=0;j<500;j++)//生成符合条件的HashMap            {                ArrayList<Integer> a=new ArrayList<Integer>();                for(int z=0;z<5;z++)                    a.add(z);                h.put(j, a);            }            //清空            long times1=System.currentTimeMillis();            h.clear();            long timee1=System.currentTimeMillis();            sum+=(timee1-times1);        }        System.out.println("clear一个HashMap "+iter+" 次所花费的时间为:"+sum);        //new一个新的HashMap        long times2=System.currentTimeMillis();        for(int i=0;i<iter;i++)        {            HashMap<Integer,ArrayList> tnh=new HashMap<Integer,ArrayList>();        }        long timee2=System.currentTimeMillis();        System.out.println("new "+iter+" 个HashMap所花费的时间为:"+(timee2-times2));    }    /*output:     * clear一个HashMap 500 次所花费的时间为:0        new 500 个HashMap所花费的时间为:9*/}
0 0
原创粉丝点击