V
V
Vadim Nikiforov2021-07-16 17:36:33
.NET
Vadim Nikiforov, 2021-07-16 17:36:33

Why is StringBuilder needed? When should you use StringBuilder? What will we gain by using StringBuilder?

When should you use StringBuilder? The string has a method String.Concat, there is an overloaded operator, +that is, everything that can be done by StringBuilder can be done with the usual methods of the term. Why is StringBuilder needed?

Here we have two huge strings, each conditionally 1 gigabyte each. Here we concatenate them with the help String.Concatwe get the third string 2 gigabytes long. Let's do the same with StringBuilder. What will we win?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ayazer, 2021-07-16
@nikifovadim

look better at an example when you have 1000 lines of 1mb.
1000 rows of 1mb each = 1GB of memory allocation on load, and another (1+1000)/2 * 1000 ~ 500GB of memory allocation to store intermediate results (2mb sum of the first two, 3mb sum of the first 3x, 4mb sum of the first 4...)
in the case of a stringbuilder, you will have 1GB of memory allocation on boot + 1GB more to collect one mega string from all this

V
Vladimir Korotenko, 2021-07-17
@firedragon

The most important thing in a builder is speed. It's very noticeable when building html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question