'string'에 해당되는 글 1건

  1. 2008.11.06 String, StringBuffer의 차이점
기술정보2008. 11. 6. 22:49

본 내용은 정확하지 않을 수 있으며, 어디까지나 제 생각에 의해 정리된 내용입니다.


SUN
에서 언급한
string Buffer(http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html)의 내용을 대충 살펴보자면, String Buffer는 가변성 문자열로 String과 비슷하지만 변경이 가능하며, String Buffer에 포함된 Method를 호출 함으로써 어느 지점의 문자열이든 변경 할 수 있다고 하네요. 또한 쓰레드 상에서 안전하다는 언급이 되어있습니다.


.............
생략…………….
 

StringBufferappendinsert methods는 어떠한 데이터 타입도 수용가능 하도록 오버로드 되어있으며, 또한 효과적으로 데이터를 String으로 컨버터에서 String Buffer로 보낸다고 합니다. Append메소드는 문자열을 Buffer끝에 추가하며, insert는 지정된 위치에 추가 합니다.

 

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

 

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

 

.............생략…………….

 

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.


 

 
그렇다면 String StringBuffer의 차이점은?

String은 불가변성으로 문자열을 저장하게 되면 특정 위치에 입력된 문자열만큼 메모리를 할당 받아 쓰게 됩니다.


StringBuffer
는 가변성으로 문자열을 저장하게 되면 특정 위치에 일정 크기의 메모리를 할당 받아 쓰게 됩니다.

 

, String에 의해서 저장된 문자열은 글에 대한 수정이 안되며 수정이 된다면 그것은 문자열만큼 다시 메모리를 할당 받아 쓰는 것입니다. 하지만 StringBuffer는 문자열이 입력될 때 마다 일정 부분만큼 메모리를 다시 할당 받아 그 글을 입력하게 됩니다.

 

간단히 요약 하자면 String에 의해서 만들어진 변수가 있다고 하면 글이 쓰일 때마다 입력된 글만큼 메모리를 끌어오지만 StringBuffer는 글자가 입력될 때마다 메모리 크기를 늘려간다. StringBuffer는 메모리 위치가 변경 되지 않지만 String은 글이 입력될 때마다 메모리 주소가 바뀐다는 정도로 설명 할 수 있겠다.

 

 

그렇다면 무엇이 더 효율적일까?

String StringBuffer는 건물을 새로 짓는지 아니면 규모를 키워 가는지로 보시면 됩니다. 즉 문자열의 크기가 작을 때는 둘 다 비슷합니다. 오히려 String이 빠를 가능성도 있습니다. 하지만 문자열이 계속 늘어나는 상황이라면 StringBuffer가 빠르다고 생각합니다.

그 이유는 “aaaaaaaaaa” 10자리의 문자열에 “aaaaaaaaaa” 다시 10자리를 붙이는 상황이라면 String 20개의 공간을 다시 잡아야 하지만 StringBuffer 10개의 공간만 늘리면 되기 때문입니다.

  

String str = “a”;       위치 1

Str += “b”;             위치 3

Str += “c”;             위치 11

Str += “d”;             위치 50

 

StringBuffer strbf = new StringBuffer();

Strbg.append(“a”);         위치 1

Strbg.append(“b”);         위치 1

Strbg.append(“c”);          위치 1

Strbg.append(“d”);          위1


위 내용 처럼, String은 변수에 내용이 저장될 때 마다 그만큼의 메모리를 받아오며 그때 마다 위치는 달라질 수 있다. 하지만 StringBuffer는 처음 위치에서 메모리 크기만을 늘려가면서 문자열을 더하게 된다.

  

Posted by Jake Kim