避免创建不必要的对象

2018-09-05  本文已影响0人  SetsunaHao

在编码中尽量减少大对象的使用,创建对象的成本是非常高的。

举个栗子:

代码块一

  public static void main(String[] args) {

        long start = System.currentTimeMillis();
        long sum = 0l;
        for (int i = 0 ;i < Integer.MAX_VALUE; i ++){
            sum += i;
        }
        long end = System.currentTimeMillis();

        System.out.println("cost time : " + (end - start));
    }
    
    cost time : 1025

代码块二

 public static void main(String[] args) {

        long start = System.currentTimeMillis();
        Long sum = 0l;
        for (int i = 0 ;i < Integer.MAX_VALUE; i ++){
            sum += i;
        }
        long end = System.currentTimeMillis();

        System.out.println("cost time : " + (end - start));
    }

cost time : 8983

在代码块一中我们使用的是long类型,代码块二中我们使用了Long,程序构造了2^31个Long实例,所以在程序中要注意基本类型和装箱类型的使用。

上一篇 下一篇

猜你喜欢

热点阅读