首页 > 代码库 > 五、避免创建不必要的对象

五、避免创建不必要的对象

一般来说,对于java的对象来说,可以重用对象的情况下:尽量不要在需要的时候就创建一个相同功能的对象

1、String

@Test    public void test02() {        btime=System.currentTimeMillis();        for(long i=0;i<1000000000;i++){            String a=new String("a");        }        etime=System.currentTimeMillis();        System.out.println(etime-btime);        //这种方式创建String对象10亿次花了9574        }        @Test    public void test03() {        btime=System.currentTimeMillis();        for(long i=0;i<1000000000;i++){            String a="a";        }        etime=System.currentTimeMillis();        System.out.println(etime-btime);        //这种方式花了2337    }

 

2、尽量用静态初始化一些相同功能的对象

class Person231 {    private final Date birth = new Date();    public boolean isBabyBoomer() {        Calendar g = Calendar.getInstance();        g.set(1946, Calendar.JANUARY, 1, 0, 0);        Date start = g.getTime();        g.set(1965, Calendar.JANUARY, 1, 0, 0);        Date end = g.getTime();        return birth.before(end) && birth.after(start);    }}
@Test    public void test21() {        Person231 p=new Person231();                btime=System.currentTimeMillis();        for(long i=0;i<10000000;i++){            p.isBabyBoomer();        }        etime=System.currentTimeMillis();        System.out.println(etime-btime);    }//调用一千万次,花了27585

 

改进后:

class Person231 {        private final static Date birth = new Date();    private static Calendar g;    private static Date start;    private static Date end;    static{        g= Calendar.getInstance();        g.set(1946, Calendar.JANUARY, 1, 0, 0);        start=g.getTime();        g.set(1965, Calendar.JANUARY, 1, 0, 0);        end=g.getTime();    }    public boolean isBabyBoomer() {                return birth.before(end) && birth.after(start);    }}
       @Test    public void test21() {        Person231 p=new Person231();                btime=System.currentTimeMillis();        for(long i=0;i<10000000;i++){            p.isBabyBoomer();        }        etime=System.currentTimeMillis();        System.out.println(etime-btime);    }//调用一千万次,花了148    

 

 

3、基本类型及其包装类---优先使用基础类

//使用包装类,每使用一次创建一个对应类@Test    public void test20() {        int i = Integer.MAX_VALUE;        System.out.println(i);        Long sum = 0L;        btime = System.currentTimeMillis();        for (int j = 0; j < i; j++) {            sum = sum + j;        }        etime = System.currentTimeMillis();        System.out.println(etime - btime);    }// 调用2147483647次,花了28551
@Test    public void test20() {        //使用基本类型        int i = Integer.MAX_VALUE;        System.out.println(i);        long sum = 0L;        btime = System.currentTimeMillis();        for (int j = 0; j < i; j++) {            sum = sum + j;        }        etime = System.currentTimeMillis();        System.out.println(etime - btime);    }// 调用2147483647次,花了5151

 

五、避免创建不必要的对象