zoukankan      html  css  js  c++  java
  • 条目5:避免创建不必要的对象

    避免创建不必要的对象


    1.自动装箱和拆箱。要优先使用简单数据类型,而不是装箱的简单类型。避免无意识的装箱。

    public class Sum {
        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("使用Long耗时:="+(end-start));
    
    
            long start1 = System.currentTimeMillis();
            long sum1 = 0L;
            for(int i=0;i<Integer.MAX_VALUE;i++){
                sum1+=i;
            }
            long end1 = System.currentTimeMillis();
            System.out.println("使用long耗时:="+(end1-start1));
    
        }
    }
    

    2.重用那些已知的不会修改的可变对象

    class Person {
        private final Date birthDate;
    
        public Person(Date birthDate) {
            // Defensive copy - see Item 39
            this.birthDate = new Date(birthDate.getTime());
        }
    
        // Other fields, methods
    
        /**
         * The starting and ending dates of the baby boom.
         */
        private static final Date BOOM_START;
        private static final Date BOOM_END;
    
        static {
            Calendar gmtCal =
                Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
            BOOM_START = gmtCal.getTime();
            gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
            BOOM_END = gmtCal.getTime();
        }
    
        public boolean isBabyBoomer() {
            return birthDate.compareTo(BOOM_START) >= 0 &&
                   birthDate.compareTo(BOOM_END)   <  0;
        }
    }
    
  • 相关阅读:
    hdu 1853 Cyclic Tour 最小费用最大流
    hdu 2686 Matrix 最小费用最大流
    hdu 1533 Going Home 最小费用最大流
    hdu 2883 kebab 网络流
    hdu 4240 Route Redundancy 最大流
    hdu 4292 Food 最大流
    使用Windows Azure创建Windows系统虚拟机-下
    使用Windows Azure创建Windows系统虚拟机-上
    Windows Azure公有云服务相关方案
    使用Windows Azure创建Linux系统虚拟机-下
  • 原文地址:https://www.cnblogs.com/tisakong/p/4476661.html
Copyright © 2011-2022 走看看