String vs StringBuffer

우연히 들린 블로그에 다음과 같은 글이 있길래..나도 한번 실제적으로 테스트를 해봤다.
http://blog.naver.com/korcslewis?Redirect=Log&logNo=110001384963

String과 StringBuffer의 성능에 대한 이야기는 자주 언급되는 퍼포먼스 튜닝 중의 하나의 요소이다. .

과연 얼마나 차이가 나는 것일까? JDK5.0을 사용해서 하면 내부적으로 컴파일하는 것이 틀리다는 얘기도 있다. 그래서, 나도 간단하게 얼마나 차이가 나는 것인가를 Junit으로 체크해보았다
테스트환경
JAVA : jdk1.5.0_06
OS : 윈도우XP


public void test_String(){
  Runtime rt = Runtime.getRuntime();
     System.out.print(rt.freeMemory());
     System.out.println("/" + rt.totalMemory());
     long start = System.currentTimeMillis();
     String a = "a";
     for(int i=0; i < 30000; i++) {
      a += "a";
    }
    long stop = System.currentTimeMillis();
    System.out.println("time: " + (stop - start) );
    System.out.print(rt.freeMemory());
    System.out.println("/" + rt.totalMemory());
}
Result
1585312/2031616
time: 3415
688904/2031616


public void test_StringBuffer(){
  Runtime rt = Runtime.getRuntime();
    System.out.print(rt.freeMemory());
     System.out.println("/" + rt.totalMemory());
     long start = System.currentTimeMillis();
     StringBuffer a = new StringBuffer("a");
     for(int i=0; i < 30000; i++) {
      a.append("a");
    }
    long stop = System.currentTimeMillis();
    System.out.println("time: " + (stop - start) );
    System.out.print(rt.freeMemory());
    System.out.println("/" + rt.totalMemory());
    System.out.print(rt.freeMemory());
    System.out.println("");
}
Result
1586784/2031616
time: 10
1427216/2031616

런타임 시간과 메모리에 차이가 절대적인 비교는 어렵겠지만, 대략 이정도 차이가 난다는 것을 알수가 있다. 물론, 상황(환경)에 따라 좀더 차이가 적어질 수도 커질수도 있으나, 어떤 API를 선택하는냐는 여러분의 몫이다!!

가급적 StringBuffer를 사용하자는 글...너무 오래된 아티클이라...^^;
http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

항상 StringBuffer의 선택이 좋은 퍼포먼스를 보이지 않을수 있다는 글!!
http://xper.org/wiki/xp/StringBuffer

String vs StringBuffer에 대한 장문의 기술토론!!
http://www.javaservice.net/~java/bbs/read.cgi?m=qna&b=discussion&c=r_p&n=1053403354
Posted by ologist
 TAG ,

블로그 이미지
ologist

공지사항

Yesterday221
Today25
Total34,406

달력

 « |  » 2012.02
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

최근에 받은 트랙백

글 보관함