웹사이트 검색

문자열 대 StringBuffer 대 StringBuilder


String은 Java에서 가장 널리 사용되는 클래스 중 하나입니다. StringBuffer 및 StringBuilder 클래스는 문자열을 조작하는 메서드를 제공합니다. StringBuffer와 StringBuilder의 차이점을 살펴보겠습니다. StringBuffer 대 StringBuilder는 인기 있는 Java 인터뷰 질문입니다.

문자열 대 StringBuffer 대 StringBuilder

문자열은 코어 자바 인터뷰에서 가장 중요한 주제 중 하나입니다. 콘솔에 무엇인가를 출력하는 프로그램을 작성하고 있다면 String을 사용하고 있는 것입니다. 이 튜토리얼은 String 클래스의 주요 기능에 초점을 맞추는 것을 목표로 합니다. 그런 다음 StringBuffer 및 StringBuilder 클래스를 비교합니다.

자바의 문자열

  1. String class represents character strings, we can instantiate String in two ways.

    String str = "ABC";
    // or 
    String str = new String("ABC");
    
  2. String is immutable in Java. So it’s suitable to use in a multi-threaded environment. We can share it across functions because there is no concern of data inconsistency.

  3. When we create a String using double quotes, JVM first looks for the String with the same value in the string pool. If found, it returns the reference of the string object from the pool. Otherwise, it creates the String object in the String pool and returns the reference. JVM saves a lot of memory by using the same String in different threads.

  4. If the new operator is used to create a string, it gets created in the heap memory.

  5. The + operator is overloaded for String. We can use it to concatenate two strings. Although internally it uses StringBuffer to perform this action.

  6. String overrides equals() and hashCode() methods. Two Strings are equal only if they have the same character sequence. The equals() method is case sensitive. If you are looking for case insensitive checks, you should use equalsIgnoreCase() method.

  7. The string uses UTF-16 encoding for the character stream.

  8. String is a final class. All the fields as final except “private int hash”. This field contains the hashCode() function value. The hashcode value is calculated only when the hashCode() method is called for the first time and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations. So every time the hashCode() method is called, it will result in the same output. For the caller, it seems like calculations are happening every time but internally it’s cached in the hash field.

문자열 대 StringBuffer

문자열은 Java에서 변경할 수 없기 때문에 연결, 하위 문자열 등과 같은 문자열 조작을 수행할 때마다 새 문자열을 생성하고 가비지 수집을 위해 이전 문자열을 버립니다. 이것은 무거운 작업이며 힙에 많은 쓰레기를 생성합니다. 따라서 Java는 문자열 조작에 사용해야 하는 StringBuffer 및 StringBuilder 클래스를 제공했습니다. StringBuffer 및 StringBuilder는 Java에서 변경 가능한 객체입니다. 문자열 조작을 위해 append(), insert(), delete() 및 substring() 메서드를 제공합니다.

StringBuffer 대 StringBuilder

StringBuffer는 Java 1.4까지 문자열 조작을 위한 유일한 선택이었습니다. 그러나 모든 공용 메서드가 동기화된다는 단점이 있습니다. StringBuffer는 스레드 안전성을 제공하지만 성능 비용이 있습니다. 대부분의 시나리오에서 다중 스레드 환경에서는 String을 사용하지 않습니다. 그래서 Java 1.5는 스레드 안전성과 동기화를 제외하고는 StringBuffer와 유사한 새로운 클래스 StringBuilder를 도입했습니다. StringBuffer에는 하위 문자열, 길이, 용량, trimToSize 등과 같은 몇 가지 추가 메서드가 있습니다. 그러나 이러한 메서드는 String에도 모두 있기 때문에 필요하지 않습니다. 이것이 이러한 메서드가 StringBuilder 클래스에서 구현되지 않은 이유입니다. StringBuffer는 Java 1.0에서 도입되었지만 StringBuilder 클래스는 StringBuffer의 단점을 살펴보고 Java 1.5에서 도입되었습니다. 단일 스레드 환경에 있거나 스레드 안전에 관심이 없다면 StringBuilder를 사용해야 합니다. 그렇지 않으면 스레드로부터 안전한 작업에 StringBuffer를 사용하십시오.

StringBuilder 대 StringBuffer 성능

StringBuffer와 StringBuilder 객체에 대해 append()를 여러 번 수행하는 샘플 프로그램과의 동기화로 인해 성능에 미치는 영향을 확인하려고 합니다.

package com.journaldev.java;

import java.util.GregorianCalendar;

public class TestString {

	public static void main(String[] args) {
		System.gc();
		long start=new GregorianCalendar().getTimeInMillis();
		long startMemory=Runtime.getRuntime().freeMemory();
		StringBuffer sb = new StringBuffer();
		//StringBuilder sb = new StringBuilder();
		for(int i = 0; i<10000000; i++){
			sb.append(":").append(i);
		}
		long end=new GregorianCalendar().getTimeInMillis();
		long endMemory=Runtime.getRuntime().freeMemory();
		System.out.println("Time Taken:"+(end-start));
		System.out.println("Memory used:"+(startMemory-endMemory));
	}
}

시간과 메모리 값을 확인하기 위해 StringBuffer 개체에 대해서도 동일한 코드를 실행했습니다. 각 경우에 대해 코드를 5번 실행한 다음 평균값을 계산했습니다.

Value of i StringBuffer (Time, Memory) StringBuilder (Time, Memory)
10,00,000 808, 149356704 633, 149356704
1,00,00,000 7448, 147783888 6179, 147783888

단일 스레드 환경의 경우에도 StringBuilder가 StringBuffer보다 성능이 좋은 것은 분명합니다. 이러한 성능 차이는 StringBuffer 메서드의 동기화로 인해 발생할 수 있습니다.

문자열 대 StringBuffer 대 StringBuilder

  1. String은 불변인 반면 StringBuffer와 StringBuilder는 가변 클래스입니다.
  2. StringBuffer는 스레드로부터 안전하고 동기화되지만 StringBuilder는 그렇지 않습니다. 이것이 StringBuilder가 StringBuffer보다 빠른 이유입니다.
  3. 문자열 연결 연산자(+)는 내부적으로 StringBuffer 또는 StringBuilder 클래스를 사용합니다.
  4. 멀티 스레드가 아닌 환경에서 문자열을 조작하려면 StringBuilder를 사용해야 하고 그렇지 않으면 StringBuffer 클래스를 사용해야 합니다.

String, StringBuffer 및 StringBuilder 간의 차이점을 빠르게 정리하기 위한 것입니다. StringBuilder는 대부분의 일반적인 프로그래밍 시나리오에서 StringBuffer보다 더 적합합니다. 참조:

  • 문자열 API 문서
  • StringBuffer API 문서
  • StringBuilder API 문서