Java

Java - String.replace(), String.replaceAll() 차이

codeManager 2023. 3. 3. 23:33
반응형

자바에서 문자열의 특정 문자를 대치해줄 때 replace() 함수를 사용합니다.

 

String.replace(), String.replaceAll() 두 함수가 어떤 차이가 있는지 알아보겠습니다.

 

String test = "ABCCDDD";
System.out.println(test.replace("C", "D"));
System.out.println(test.replaceAll("C", "D"));

 

이러면 코드의 결과는 두개가 동일합니다.

 

둘다 특정 문자를 대치해주는 함수이므로 결과는 같지만 내부 구현이 다르기 때문에 성능이 차이가 있습니다.

 

 

String.replace() 함수의 실제 구현 부분입니다.

public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
                                : StringUTF16.replace(value, oldChar, newChar);
        if (ret != null) {
            return ret;
        }
    }
    return this;
}

 

 

String.replaceAll() 구현 부분

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

 

replaceAll()의 경우는 Pattern을 사용하고 있습니다.

 

정규표현식용 Pattern 인스턴스는 한 번 쓰고 버려져서 곧바로 가비지 컬렉션 대상이 되고,  인스턴스 생성 비용이 높습니다.

 

그래서 성능이 중요하게 생각되는 경우에는 replaceAll 대신 replace를 쓰는 것이 좋습니다.

 
반응형