NMP-Study / EffectiveJava2022

Effective Java Study 2022
5 stars 0 forks source link

아이템 6. 불필요한 객체 생성을 피하라 #6

Closed okhee closed 2 years ago

mbyul commented 2 years ago

객체의 재사용

String ossId1 = new String("yunjh.1216"); String ossId2 = new String("yunjh.1216"); System.out.println(ossId1 == ossId2); // false


## 정적 팩토리 메서드 사용
- #1 : 불변 클래스의 정적 팩토리 메서드
  - 불변 클래스의 생성자는 자바 9에서 deprecated API 로 지정 되었음
~~~java
Boolean isJungHyeOssId = Boolean.valueOf("yunjh.1217");
    /**
     * Returns a {@code Boolean} instance representing the specified
     * {@code boolean} value.  If the specified {@code boolean} value
     * is {@code true}, this method returns {@code Boolean.TRUE};
     * if it is {@code false}, this method returns {@code Boolean.FALSE}.
     * If a new {@code Boolean} instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Boolean(boolean)}, as this method is likely to yield
     * significantly better space and time performance.
     *
     * @param  b a boolean value.
     * @return a {@code Boolean} instance representing {@code b}.
     * @since  1.4
     */
    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

    /**
     * The {@code Boolean} object corresponding to the primitive
     * value {@code true}.
     */
    public static final Boolean TRUE = new Boolean(true);

    /**
     * The {@code Boolean} object corresponding to the primitive
     * value {@code false}.
     */
    public static final Boolean FALSE = new Boolean(false);

생성 비용이 값비싼 객체를 재사용 (ex> java.util.regex.Pattern)

private void removeByline(List sentences) { sentences.set(lastIndex, sentences.get(lastIndex).matches(BYLINE_EMAIL_REGEX).trim()); } // TO-BE private static final String BYLINE_REPORTER_REGEX = "[가-힣]{2,4} ?기자"; private static final Pattern BYLINE_REPORTER_PATTERN = Pattern.compile(BYLINE_REPORTER_REGEX, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

private void removeByline(List sentences) { sentences.set(lastIndex, BYLINE_REPORTER_PATTERN.matcher(sentences.get(lastIndex)).matches().trim()); }

- 지연 초기화(#83) 
    - removeByline 메서드가 호출될 때  필드를 초기화함 (권하지 않음)
    - 지연 초기화는 코드를 복잡하게 만드는데, 성능은 크게 개선되지 않을 때가 많다. (#67)

## 어탭터
- 어댑터는 인터페이스를 통해 뒤에 있는 객체로 연결해주는 view여서 여러개 만들 필요가 없다.
- 같은 인스턴스를 대변하는 여러 개의 인스턴스 생성은 피하자

~~~java
Map<String, Object> map = new HashMap<>();
map.put("Effictive", "Java");

Set<String> set1 = map.keySet();
Set<String> set2 = map.keySet();

assertThat(set1).isSameAs(set2); // TRUE

set1.remove("Java");
System.out.println(set1.size()); // 1
System.out.println(set1.size()); // 1

오토박싱(auto boxing)

image image
mbyul commented 2 years ago

"새로운 객체를 만들어야 한다면 기존 객체를 재사용하지 마라(#50)" 과 대조적