티스토리 뷰

개발

string vs stringbuilder vs stringbuffer

달리는개발자 2019. 3. 22. 23:07

String은 자바에서 가장 많이 사용하는 클래스 중 하나이다.

String은 불변객체(immutable) 이고, StringBuffer는 가변객체(mutable)이다

이 말은 String 연산은 항상 새로운 객체를 생성하고 StringBuffer 그렇지 않다는 이야기이다.



요즘은 위와 같은 String + 연산은 자바 컴파일러가 StringBuilder 또는 StringBuffer로 대체한다.

15.18.1. String Concatenation Operator +

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.


The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.


The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).


An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

bytecode로 컴파일된 class 파일을 다음 명령어로 확인할 수 있다.

]$ javap -c StringTest.class


StringBuilder와 StringBuffer의 차이는 동기화.

StringBuffer는 Thread-Safe 하지만 성능은 StringBuilder보다 느리다.



참고

http://www.java67.com/2012/08/difference-between-string-and-stringbuffer-in-java.html

https://www.baeldung.com/java-string-builder-string-buffer

https://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html

https://dzone.com/articles/string-concatenation-performacne-improvement-in-ja

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 30 31
글 보관함