program story

C #에서 문자열과 StringBuilder의 차이점

inputbox 2020. 11. 8. 09:53
반응형

C #에서 문자열과 StringBuilder의 차이점


string의 차이점은 무엇입니까 StringBuilder?

또한 이해를위한 몇 가지 예는 무엇입니까?


string인스턴스는 불변이다. 생성 된 후에는 변경할 수 없습니다. 대신 문자열을 변경하는 것으로 보이는 모든 작업은 새 인스턴스를 반환합니다.

string foo = "Foo";
// returns a new string instance instead of changing the old one
string bar = foo.Replace('o', 'a');
string baz = foo + "bar"; // ditto here

불변 객체는 동기화 문제를 두려워하지 않고 스레드 전체에서 사용할 수 있거나 누군가가 변경해서는 안되는 객체를 변경하는 것을 두려워하지 않고 개인 백업 필드를 직접 전달할 수있는 등의 좋은 속성을 가지고 있습니다 (배열 또는 변경 가능한 목록 참조, 원하지 않는 경우 반환하기 전에 복사해야하는 경우가 많습니다.) 그러나 부주의하게 사용하면 심각한 성능 문제가 발생할 수 있습니다 (거의 모든 것과 같이 실행 속도를 자랑하는 언어의 예제가 필요하면 C의 문자열 조작 함수를 살펴보십시오).

부분적으로 구성하거나 많은 것을 변경하는 것과 같이 변경 가능한 문자열 이 필요할 때 변경할 있는 StringBuilder문자의 버퍼 인 a가 필요합니다 . 이것은 대부분 성능에 영향을 미칩니다. 변경 가능한 문자열을 원하고 대신 일반 인스턴스로 수행하면 불필요하게 많은 객체를 생성하고 파괴하는 반면 인스턴스 자체는 변경되어 많은 새 객체가 필요 하지 않게 됩니다.stringStringBuilder

간단한 예 : 다음은 많은 프로그래머를 고통스럽게 만들 것입니다.

string s = string.Empty;
for (i = 0; i < 1000; i++) {
  s += i.ToString() + " ";
}

여기서는 2001 개의 문자열을 만들게되는데 그중 2000 개는 버려집니다. StringBuilder를 사용하는 동일한 예 :

StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++) {
  sb.Append(i);
  sb.Append(' ');
}

이것은 메모리 할당 자에 훨씬 적은 스트레스를 가할 것입니다 :-)

그러나 C # 컴파일러는 문자열과 관련하여 상당히 똑똑하다는 점에 유의해야합니다. 예를 들어, 다음 줄

string foo = "abc" + "def" + "efg" + "hij";

컴파일러에 의해 결합되어 런타임에 단일 문자열 만 남습니다. 마찬가지로

string foo = a + b + c + d + e + f;

다시 작성됩니다

string foo = string.Concat(a, b, c, d, e, f);

그래서 당신은 그것을 처리하는 순진한 방법이 될 5 개의 무의미한 연결에 대해 지불 할 필요가 없습니다. 이것은 위와 같이 루프에 저장되지 않습니다 (컴파일러가 루프를 풀지 않는 한 JIT 만 실제로 그렇게 할 수 있고 그것에 내기하지 않는 것이 좋습니다).


문자열은 변경할 수 없으므로 문자열을 만들 때 변경할 수 없습니다. 오히려 새 값을 저장하기 위해 새 문자열을 생성하며 문자열 변수의 값을 많이 변경해야하는 경우 비효율적 일 수 있습니다.

StringBuilder는 변경 가능한 문자열을 시뮬레이션하는 데 사용할 수 있으므로 문자열을 많이 변경해야 할 때 유용합니다.


문자열 대 StringBuilder

    • 시스템 네임 스페이스에서
    • 불변 (읽기 전용) 인스턴스
    • 지속적인 가치 변화가 발생하면 성능이 저하됩니다.

    • 스레드로부터 안전

  • StringBuilder (변경 가능한 문자열)

    1. System.Text 네임 스페이스에서
    2. 가변 인스턴스
    3. 기존 인스턴스에 새로운 변경 사항이 적용되므로 더 나은 성능을 보여줍니다.

ObjectIDGenerator를 사용하는 많은 예제와 함께이 주제에 대한 설명 문서를 보려면 이 링크를 따르십시오 .

관련 스택 오버플로 질문 : C #에서 문자열이 변경되지 않을 때 문자열의 변경 가능성


String 인스턴스는 불변입니다. 즉, 생성 된 후에는 변경할 수 없습니다. 문자열에 대해 작업을 수행하면 기존 인스턴스 값을 수정하는 대신 새 인스턴스 (메모리에 새 인스턴스 생성)를 반환합니다.

StringBuilder

StringBuilder는 변경 가능합니다. 즉, StringBuilder에서 작업을 수행하면 기존 인스턴스 값을 업데이트하고 새 인스턴스를 만들지 않습니다.

String과 StringBuilder의 차이점


로부터 의 StringBuilder 클래스 문서 :

String 개체는 변경할 수 없습니다. System.String 클래스의 메서드 중 하나를 사용할 때마다 메모리에 새 문자열 개체를 만들고 새 개체에 대한 공간을 새로 할당해야합니다. 문자열을 반복적으로 수정해야하는 상황에서는 새 String 개체를 만드는 것과 관련된 오버 헤드로 인해 비용이 많이들 수 있습니다. System.Text.StringBuilder 클래스는 새 개체를 만들지 않고 문자열을 수정하려는 경우에 사용할 수 있습니다. 예를 들어 StringBuilder 클래스를 사용하면 루프에서 여러 문자열을 함께 연결할 때 성능이 향상 될 수 있습니다.


A StringBuilder will help you when you need to build strings in multiple steps.

Instead of doing this:

String x = "";
x += "first ";
x += "second ";
x += "third ";

you do

StringBuilder sb = new StringBuilder("");
sb.Append("first ");
sb.Append("second ");
sb.Append("third");
String x = sb.ToString();

The final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.


Major difference:

String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.

Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.

String is the only class that can have a reference literal.


Strings are immutable i.e if you change their value, the old value will be discarded and a new value is created on the heap, whereas in string builder we can modify the existing value without the new value being created.

So performance-wise String Builder is beneficial as we are needlessly not occupying more memory space.


A String (System.String) is a type defined inside the .NET framework. The String class is not mutable. This means that every time you do an action to an System.String instance, the .NET compiler create a new instance of the string. This operation is hidden to the developer.

A System.Text.StringBuilder is class that represents a mutable string. This class provides some useful methods that make the user able to manage the String wrapped by the StringBuilder. Notice that all the manipulations are made on the same StringBuilder instance.

Microsoft encourages the use of StringBuilder because it is more effective in terms of memory usage.


Also the complexity of concatenations of String is O(N2), while for StringBuffer it is O(N).

So there might be performance problem where we use concatenations in loops as a lot of new objects are created each time.


You can use the Clone method if you want to iterate through strings along with the string builder... It returns an object so you can convert to a string using the ToString method...:)


System.String is a mutable object, meaning it cannot be modified after it’s been created. Please refer to Difference between string and StringBuilder in C#? for better understanding.


A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.

A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.

Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

참고URL : https://stackoverflow.com/questions/3069416/difference-between-string-and-stringbuilder-in-c-sharp

반응형