C# When to use string classes in C#?

  • Thread starter Thread starter mcodesmart
  • Start date Start date
  • Tags Tags
    Classes String
Click For Summary
Immutable string classes in C# are essential for efficiency, particularly because they can share storage for identical objects, reducing overhead associated with creating and destroying temporary objects. In object-oriented programming, seemingly harmless operations can lead to unnecessary object creation, but immutable strings mitigate this issue. Mutable strings, such as those managed by the StringBuilder class, should only be used when the string's contents are expected to change after creation. StringBuilder pre-allocates a large array for characters, minimizing the need for repeated memory allocation during extensive string concatenation, making it significantly more efficient in scenarios involving heavy string manipulation.
mcodesmart
Messages
34
Reaction score
0
We have a string builder class which is mutable in C#. Why do we need immutable string classes?
 
Technology news on Phys.org
Basically, for efficiency. for example the immutable classes can share storage for identical objects. Harmless-looking statements in an object oriented language can often create and destroy temporary objects, and the overheads are much smaller if the contents of these are known to be immutable.

You should only use mutable strings if you know the contents of the string may change after you have created it.
 
A StringBuilder class just pre-allocates a big array to hold the characters of a string you are yet to create. It prevents the need to call the allocator over and over again if concatenating a bunch of (immutable) shorter strings.

When there is a LOT of string concatenation going on at runtime, it is often more efficient (significantly more) to use StringBuilder.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 34 ·
2
Replies
34
Views
4K
  • · Replies 9 ·
Replies
9
Views
1K
  • · Replies 47 ·
2
Replies
47
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 118 ·
4
Replies
118
Views
9K