《Effective Java》第5条:避免创建不必要的对象

原文地址: itweknow.cn/detail?id=6… ,欢迎大家访问。

当一个对象能够被重用的时候,就不要去创建新对象。我们先来考虑一个比较简单的例子

String s = new String("stringette");
复制代码

这个语句在每次被调用的时候都会创建一个全新的String实例,而且参数stringette自身也是一个String实例。所以一般建议使用下面的方式来申明一个String

String s = "stringette";
复制代码

下面通过几个例子来说明一下为啥需要避免创建不必要的对象。

例一

我们有一个Person类,并且类里面有一个isBabyBoomer方法,用来校验这个人是否在生育高峰期出生(生育高峰期为1946年至1964年),可能我们通常的写法是

public class Person {

    private final Date birthDate;

    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }

    public boolean isBabyBoomer() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        // 高峰期开始时间。
        calendar.set(1946, Calendar.JANUARY, 1,
                0, 0, 0);
        Date start = calendar.getTime();
        // 高峰期结束时间。
        calendar.set(1965, Calendar.JANUARY, 1,
                0, 0, 0);
        Date end = calendar.getTime();
        // 比较。
        return birthDate.compareTo(start) >=0 &&
                birthDate.compareTo(end) < 0;
    }
}
复制代码

我们来试一下调用一千万次这个方法所消耗的时间。

public class Test01 {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Person person = new Person(new Date());
        for (int i=0; i<10000000; i++) {
            person.isBabyBoomer();
        }
        long end = System.currentTimeMillis();
        System.out.println("消耗时间:" + (end - start) + "ms");
    }
}
复制代码

在我的电脑上耗时在3200ms左右,下面我们做一下修改,将生育高峰期的开始和结束时间抽出来作为Person类的属性,并且在静态代码块中进行赋值。

public class Person {

    private final Date birthDate;

    private static final Date startDate;

    private static final Date endDate;

    static {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        // 高峰期开始时间。
        calendar.set(1946, Calendar.JANUARY, 1,
                0, 0, 0);
        startDate = calendar.getTime();
        // 高峰期结束时间。
        calendar.set(1965, Calendar.JANUARY, 1,
                0, 0, 0);
        endDate = calendar.getTime();
    }

    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }
    
    public boolean isBabyBoomer2() {
        // 比较。
        return birthDate.compareTo(startDate) >=0 &&
            birthDate.compareTo(endDate) < 0; 
    }
}
复制代码

再次测试发现消耗时间大概在20ms左右,效率提高了差不多150倍。

例二

我们知道在Java中字符串如果使用+进行拼接的时候会创建新的String实例,而使用StringBuilder.append()方法则不会创建新的实例。下面我们分别用两种方式进行十万次的字符串拼接。

public class Test02 {

    public static void main(String[] args) {
        method01();
        method02();
    }

    public static void method01() {
        long start = System.currentTimeMillis();
        String a = "";
        for (int i=0; i<100000; i++) {
            a += "a";
        }
        long end = System.currentTimeMillis();
        System.out.println("method01 used time:" + (end - start) + "ms");
    }

    public static void method02() {
        long start = System.currentTimeMillis();
        StringBuilder a = new StringBuilder("");
        for (int i=0; i<100000; i++) {
            a.append("a");
        }
        long end = System.currentTimeMillis();
        System.out.println("method01 used time:" + (end - start) + "ms");
    }
}
复制代码

结果如下:

method01 used time:3591ms
method01 used time:2ms
复制代码

例三

这个例子我们直接上代码,区别很微小,就是在定义sum的时候method01使用了包装类型,method02则使用了基本类型。例子实现的是求所有int正值的和。

public class Test03 {

    public static void main(String[] args) {
        method01();
        method02();
    }
    public static void method01() {
        long start = System.currentTimeMillis();
        Long sum = 0L;
        for (long i=0; i< Integer.MAX_VALUE; i++) {
            sum += i;
        }
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println("method1 time used:" + (end - start) + "ms");
    }

    public static void method02() {
        long start = System.currentTimeMillis();
        long sum = 0L;
        for (long i=0; i< Integer.MAX_VALUE; i++) {
            sum += i;
        }
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println("method2 time used:" + (end - start) + "ms");
    }
}
复制代码

得到的结果是:

2305843005992468481
method1 time used:6170ms
2305843005992468481
method2 time used:633ms
复制代码

可以看到细微的区别结果的差距还是蛮大的,所以我们要优先使用基本类型而不是装箱基本类型,要当心无意识的自动装箱。 最终我们得到的结论是当你应该重用现有对象时,请不要创建新的对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值