ABOUT ME

Today
Yesterday
Total
  • [Java] String 연결
    우아한 테크코스/테크코스 2020. 2. 19. 21:07
    반응형

    일반 간단한 String 연결 (JDK 1.8 ~ ) 

    문자열.concat(연결할문자열);

    연결할 문자열 길이가 0이 아니라면, 내부적으로 새 문자 배열 버퍼를 만들고 해당 문자 배열을 기반으로 새 문자열 반환

    소수(대략 3개 이하)의 문자열을 연결할 경우 +보다 더 유리한 것으로 추정 

    public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        char buf[] = new char[count + otherLen];
        getChars(0, count, buf, 0);
        str.getChars(0, otherLen, buf, count);
        return new String(0, count + otherLen, buf);
    }

    문자열 + 연결할문자열

    자바 컴파일러에 의해 아래와 같이 변환되며, 개수가 많을 경우 concat보다 유리함.

    2개나 적을 경우엔 +를 통해 StringBuilder를 만드는 비용이 더 클 수 있음

    // result = strA + strB;
    result = new StringBuilder(strA).append(strB).toString();
    
    // result = strA + strB + strC + strD + strE;
    result = new StringBuilder(strA).append(strB).append(strC).append(strD).append(strE).toString();
    

    for Loop에서의 String 연결 성능

    StringBuilder > StringBuffer(thread safe) >>>>>> String#concat >>> "+"

    단, StringBuilder와 StringBuffer의 경우엔 for Loop 외부에서 생성된 객체들

    아래와 같은 결과가 나오는 이유

    for문을 돌 때 마다 "+"의 경우 내부 컴파일러가 toString()해주기 때문

    String abc = "a";
    for(int i = 0; i < 10; i++) {
        // StringBuilder로 변환된 후 연산됨
        abc += "a";
        // 여기에서 toString()으로 반환되고 반복
    }
    
    즉, 위와 같은 경우 StringBuilder 연산이 10번 반복됨

     

    출처 : http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html

    반응형

    댓글

Designed by Tistory.