시소당
String 은 Immutable(불변) 객체이기 때문에 + 를 이용하여 연결하면 "" 안의 String 객체가 + 할 때마다 생성이 된다.
// Inefficient version using String.
public static String dupl(String s, int times) {
String result = s;
for (int i=1; i<times; i++) {
result = result + s;
}
return result;
}
위와 같은 경우 String s="a";, int times = 100 이라고 할 때, 99개의 객체가 생성될
것이며, 98개의 객체는 버려질 것이다. 객체를 새로 생성하는 것은 효율적이지가 않다.
StringBuffer 를 사용해 보자.
// More efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s);
for (int i=1; i<times; i++) {
result.append(s);
}
return result.toString();
}
위 소스는 단지 두 개의 객체 StringBuffer 그리고 리턴 String 값을 생성한다.
StringBuffer 는 필요에 따라 자동으로 늘어나며 이런 확장은 손실이 크다. 더 좋은 방법은
capacity 를 정확히 정해주고 시작하는 것이다.
// Much more efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s.length() * times);
for (int i=0; i<times; i++) {
result.append(s);
}
return result.toString();
}
위에서 StringBuffer 는 정확한 capacity 를 가지고 생성되었으므로 자동으로 증가하지 않을
것이다.
StringBuilder 는 JDK 1.5 에 추가되었으며, single-threaded 환경에 적합하다.
멀티쓰레드 환경에서 문제를 발생시킬 수 있지만, 싱글쓰레드 환경에서는 동기화의 오버헤드를
피할 수 있어서 속도가 더 빠르다.
지금까지 살펴본 String 에 + 를 할 경우 안 좋은 점을 알 수 있었는데 1.5 에서는 자동으로
StringBuilder 를 사용하여 처리한다.
원본 소스
public class StringTest {
// Inefficient version using String.
public static String dupl(String s, int times) {
String result = s;
for (int i=1; i<times; i++) {
result = result + s;
}
return result;
}
public static void main(String[] args) {
String rtn = StringTest.dupl("a", 100);
}
}
디컴파일 소스
public class StringTest
{
public StringTest()
{
}
public static String dupl(String s, int times)
{
String result = s;
for(int i = 1; i < times; i++)
result = (new StringBuilder(String.valueOf(result))).append(s).
toString();
return result;
}
public static void main(String args[])
{
String rtn = dupl("a", 100);
}
}
출처 : http://hiteks3.tistory.com/6?srchid=BR1http%3A%2F%2Fhiteks3.tistory.com%2F6