불필요한 인스턴스 생성을 피하라
public class Strings {

    public static void main(String[] args) {
        String hello = "hello";

        // 같은 객체의 인스턴스를 생성해 불필요하게 메모리를 사용한다.
        String hello2 = new String("hello");

        String hello3 = "hello";

        System.out.println(hello == hello2);
        System.out.println(hello.equals(hello2));
        System.out.println(hello == hello3);
        System.out.println(hello.equals(hello3));
    }
}

 

값비싼 객체를 재사용해 성능을 개선
public class RomanNumerals {

    static boolean isRomanNumeralSlow(String s) {
        return s.matches("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
    }

    // 값비싼 객체를 재사용해 성능을 개선한다.
    private static final Pattern ROMAN = Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");

    static boolean isRomanNumberalFast(String s) {
        return ROMAN.matcher(s).matches();
    }

    public static void main(String[] args) {
        boolean result = false;

	// 패턴 인스턴스를 비교시 마다 생성
        result = isRomanNumeralSlow("MCMLXXXVI");
        System.out.println(result);

        result = isRomanNumberalFast("MCMLXXXVI");
        System.out.println(result);
    }
}

자바 정규식이 사용될만한 곳(주의)

  1. String.matches()
  2. String.split()
  3. String.replaceAll()

 

불필요한 오토박싱, 언박식을 발생에 주의하라
public class Sum {

    private static long sum() {
        Long sum = 0L;
        for (long i = 0; i <= Integer.MAX_VALUE; i++) {
            // 불필요한 오토박싱이 발생한다.
            // long to Long
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) {
        long x = 0;

        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();
            x += sum();
            long end = System.nanoTime();
            System.out.println((end - start) / 1_000_000. + " ms.");
        }

        if (x == 42) {
            System.out.println();
        }
    }
}

 

Deprecation
  • 사용 자제를 권장하고 대안을 제시하는 방법
  • @Deprecated: 컴파일시 경고 메시지를 통해 사용 자제를 권장하는 API라는 것을 클라이언트에 알려줄 수 있다.
  • @deprecated: 문서화(Javadoc)에 사용
public class RomanNumerals {

    /**
     * @deprecated in favor of
     * {@link #isRomanNumberalFast(String)}
     */
    @Deprecated(forRemoval = true, since = "1.1")
    static boolean isRomanNumeralSlow(String s) {
        return s.matches("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
    }

    private static final Pattern ROMAN = Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");

    static boolean isRomanNumberalFast(String s) {
        return ROMAN.matcher(s).matches();
    }
}

 

출처 : 백기선 이펙트브 자바 강의

+ Recent posts