读书笔记-《Effective Java》第5条:避免创建不必要的对象

 1. 这种写法每次执行都会创建一个对象(存放于堆)。

String str1 = new String("ttt");

改进后(存放于方法区常量池),当常量池已存在,则不会重复创建。

String str2 = "ttt";

2. 应优先使用基本数据类型(int、long等等),要当心无意识的自动装箱。

Integer b = 3;
int a = 123;
b = a;

3. 使用将初始化后值不再改变的代码放入静态块中,防止重复创建不必要的对象。

package org.test;

public class People {
    public People() {

    }

    static{
        System.out.println("People.static");
    }
}
package org.test;

import org.junit.Test;

public class TestTest {

    @Test
    public void test1() {
        new People();
        new People();
        new People();
    }


}

如果决定重复使用一个对象,那么就得注意安全。保护性拷贝(第39条)。

创建不必要的对象只会影响程序的风格和性能。

猜你喜欢

转载自blog.csdn.net/baitianmingdebai/article/details/85224701