Java Programming

String vs. StringBuffer vs. StringBuilder

tomato13 2009. 6. 8. 20:01

IBM RSAEE(Rational Software Analyzer Enterprise Edition)라는 도구는 JAVA 코드를 입력받아 Static analysis를 수행한다. 


아래는 대상 샘플 코드이다.


static void test1() {

int l_cnt = 0;


System.out.println(System.currentTimeMillis());

String l_str = new String(new StringBuffer(10000));

for (; l_cnt < 3000; l_cnt++) {

l_str += "긍" + "정" + "적" + "으" + "로" + "생" + "각" + "한" + "다.";

}

System.out.println(System.currentTimeMillis());

System.out.println(l_str);

}


static void test2() {

int l_cnt = 0;


System.out.println(System.currentTimeMillis());

StringBuffer sb = new StringBuffer(10000);

for (; l_cnt < 3000; l_cnt++) {

sb.append("긍");

sb.append("정");

sb.append("적");

sb.append("으");

sb.append("로");

sb.append("생");

sb.append("각");

sb.append("한");

sb.append("다.");

}

System.out.println(System.currentTimeMillis());

System.out.println(sb.toString());

}


static void test3() {

int l_cnt = 0;


System.out.println(System.currentTimeMillis());

StringBuilder sb = new StringBuilder(10000);

for (; l_cnt < 3000; l_cnt++) {

sb.append("긍");

sb.append("정");

sb.append("적");

sb.append("으");

sb.append("로");

sb.append("생");

sb.append("각");

sb.append("한");

sb.append("다.");

}

System.out.println(System.currentTimeMillis());

System.out.println(sb.toString());

}


test1()결과=>

1244458513307

1244458513557

(250 msec)


test2()결과=>

1244458513572

1244458513572

(0 msec)         // 약간 증가하기도 함


test3()결과=>

1244458513588

1244458513588

(0 msec)         // 약간 증가하기도 함


여러번 수행하였으나 test1()의 수행시간이 크게 나타났다.


RASEE의 설명은 다음과 같다.

When two strings are concatenated using + operator the new string is allocated. Thus, concatenating strings inside of loops is likely to lead to performance problems.