Java에서 String, StringBuffer 및 StringBuilder의 차이점 – 첨부된 예제
게시 됨: 2022-01-30
이 Java 자습서에서는 Java String, StringBuffer 및 StringBuilder의 차이점을 살펴보겠습니다.
시작하자:
끈:
String 클래스는 문자열을 나타냅니다. "crunchify"와 같은 Java 프로그램의 모든 문자열 리터럴은 이 클래스의 인스턴스로 구현됩니다. 문자열은 일정합니다. 값을 만든 후에는 변경할 수 없습니다.
문자열 버퍼:
스레드로부터 안전하고 변경할 수 있는 문자 시퀀스입니다. 문자열 버퍼는 문자열과 비슷하지만 수정할 수 있습니다.
특정 시점에서 특정 문자 시퀀스를 포함하지만 시퀀스의 길이와 내용은 특정 메서드 호출을 통해 변경할 수 있습니다.
문자열 버퍼는 여러 스레드에서 사용하기에 안전합니다.
스트링 빌더:
변경 가능한 문자 시퀀스입니다. 이 클래스는 StringBuffer와 호환되는 API를 제공하지만 동기화를 보장하지는 않습니다.
이 클래스는 단일 스레드에서 문자열 버퍼를 사용하던 곳(일반적으로)에서 StringBuffer의 드롭인 대체품으로 사용하도록 설계되었습니다.
가능한 경우 대부분의 구현에서 이 클래스가 더 빠르기 때문에 StringBuffer보다 우선적으로 이 클래스를 사용하는 것이 좋습니다.
아래의 String, StringBuffer, StringBuilder의 특성을 모두 비교해보자.
끈 | 문자열 버퍼 | 스트링 빌더 | |
---|---|---|---|
스레드 안전? | 네 | 네 | 아니요 |
동기화? | 네 | 네 | 아니요 |
수정 가능? | 아니요(불변) | 예(변경 가능) | 예(변경 가능) |
저장 | 문자열 풀 | 더미 | 더미 |
성능 | 느린 | 빠른 | 더 빠르게 |
자바 코드:
- 클래스 생성: CrunchifyStringVsStringBufferVsStringBuilder.java
- 거기에 아래 코드를 넣어
- 파일을 저장
이 튜토리얼에서는 총 199999번 추가, 추가 문자열을 추가합니다.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
package crunchify . com . tutorial ; /** * @author Crunchify.com * Program: Difference between String, StringBuffer and StringBuilder in Java - Example attached */ public class CrunchifyStringVsStringBufferVsStringBuilder { public static void main ( String [ ] args ) { // String: The String class represents character strings. All string literals // in Java programs, such as "abc", are implemented as instances of this class. // Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. // Because String objects are immutable they can be shared. String crunchifyString = "" ; long crunchifyBefore = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < 199999 ; i ++ ) { crunchifyString = crunchifyString + "crunchify.com" ; } long crunchifyAfter = ( System . currentTimeMillis ( ) ) ; crunchifyPrint ( "Task Completion Time for String: " + ( crunchifyAfter - crunchifyBefore ) ) ; // StringBuffer: A thread-safe, 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. crunchifyBefore = System . currentTimeMillis ( ) ; StringBuffer crunchifyStringBuffer = new StringBuffer ( ) ; for ( int i = 0 ; i < 199999 ; i ++ ) { crunchifyStringBuffer . append ( "crunchify.com" ) ; } crunchifyAfter = ( System . currentTimeMillis ( ) ) ; crunchifyPrint ( "Task Completion Time for StringBuffer: " + ( crunchifyAfter - crunchifyBefore ) ) ; // StringBuilder: A mutable sequence of characters. // This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. // This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread // (as is generally the case). Where possible, // it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. // // The principal operations on a StringBuilder 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 builder. // The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point. crunchifyBefore = System . currentTimeMillis ( ) ; StringBuilder crunchifyStringBuilder ; crunchifyStringBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < 199999 ; i ++ ) { crunchifyStringBuilder . append ( "crunchify.com" ) ; } // OR using repeat(). // crunchifyStringBuilder.append("crunchify.com".repeat(199999)); // repeat(): Returns a string whose value is the concatenation of this string repeated count times. crunchifyAfter = ( System . currentTimeMillis ( ) ) ; crunchifyPrint ( "Task Completion Time for StringBuilder: " + ( crunchifyAfter - crunchifyBefore ) ) ; } private static void crunchifyPrint ( String s ) { System . out . println ( s ) ; } } |
IntelliJ IDEA 콘솔 결과:
IntelliJ IDEA 또는 Eclipse 콘솔에서 위 프로그램을 Java 응용 프로그램으로 실행하면 아래와 같은 결과가 나타납니다.

1 2 3 4 5 6 7 8 |
/ Users / app / app / Installation / jdk - 17.0.2.jdk / Contents / Home / bin / java - javaagent : / Applications / IntelliJ IDEA . app / Contents / lib / idea_rt . jar = 50109 : / Applications / IntelliJ IDEA . app / Contents / bin - Dfile . encoding = UTF - 8 - classpath : / Users / app / . m2 / repository / org / slf4j / log4j - over - slf4j / 1.7.32 / log4j - over - slf4j - 1.7.32.jar crunchify . com . tutorial . CrunchifyStringVsStringBuffer Task Completion Time for String : 19648 Task Completion Time for StringBuffer : 7 Task Completion Time for StringBuilder : 3 Process finished with exit code 0 |
위 프로그램을 실행하는 데 문제가 있거나 String, StringBuffer 및 StringBuilder 사이에 질문이 있으면 알려주십시오.