zoukankan      html  css  js  c++  java
  • Effective Java 英文 第二版 读书笔记 Item 5:Avoid creating unnecessary objects.

    It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed.Reuse can be both faster and more stylish.An object can always be reused if it is immutable.

    String s=new String(“no”);  //DON”T DO THIS!

    The statement creates a new String instance each time it is executed.

    String s=”yes”;

    This version uses a single String instance,avoid creating unnecessary objects. 

    package creatObjects;
    
    import java.util.Calendar;
    import java.util.Date;
    import java.util.TimeZone;
    
    public class Person {
        private final Date birthDate=new Date();
        // Other fields,methods,and constructor omitted
    
        /*
         * The starting and ending dates of the baby boom.
         */
        private static final Date BOOM_START;
        private static final Date BOOM_END;
    
        //condition: this class must be invoke,otherwise it will direct  poor performance 
        static {
            Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
            // set(int year, int month, int date, int hourOfDay, int minute, int
            // second)
            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;
        }
    }

    There’s a new way to create unnecessary objects in release 1.5.It is called autoboxing,and it allows the programmer to mix primitive and boxed primitive types,boxing and unboxing automatically as needed.

    Prefer primitives to boxed primitives,and watch out for unintentional autoboxing.

    Don’t create a new object when you should reuse an existing one.

    Don’t reuse an existing object when you should create a new one.

  • 相关阅读:
    今天发现之前瑞乐做的登录和注册居然都是用的get请求,瞬间出了一身冷汗.
    用grunt进行前端工程化之路
    移动端开发库zepto 之我思
    构造高度自适应的textarea
    maxlength属性在textarea里奇怪的表现
    在windows下使用linux的开发环境
    移动web开发的一些坑
    [译]开始学习webpack
    完美解决移动Web小于12px文字居中的问题
    再谈移动端Web屏幕适配
  • 原文地址:https://www.cnblogs.com/linkarl/p/4785329.html
Copyright © 2011-2022 走看看