But if I want to concatenate 2 strings, then I assume that it is better (faster) to do this without StringBuilder. Is it correct?
This is really correct, you can find out why this is explained very well:
http://www.yoda.arachsys.com/csharp/stringbuilder.html
Calculated: if you can concatenate rows at a time, for example
var result = a + " " + b + " " + c + ..
you are better off without stringbuilder just for copying (the length of the resulting string is calculated in advance);
For structures like
var result = a; result += " "; result += b; result += " "; result += c; ..
new objects are created every time, so you should consider StringBuilder.
At the end of the article, these rules of thumb are summarized:
Thumb rules
So, when should you use StringBuilder, and when should you use string of concatenation operators?
You should definitely use StringBuilder when you join in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you will perform through the loop. For example, reading file a at a time, creating a line when you use the + = operator is potentially suicidal.
Definitely use the concatenation operator when you can (read) specify everything that should be combined in a single statement. (If you have many things to come together, consider calling String.Concat explicitly - or String.Join if you need a separator.)
Do not be afraid to break literals into several concatenated bits - the result will be the same. You can help readability by breaking a long literal into multiple lines, for example, by using no harm to performance.
If you need intermediate results of concatenating something other than submitting the next iteration of concatenation, StringBuilder is not going to help you. For example, if you create a full name from the first name and surname, and then add the third part of the information (nickname, maybe) to the end, you only benefit from using StringBuilder if you do not need (name + surname) string for other purposes (as we we do this in the example that creates the Person object).
If you just have a few concatenations to do, and you really want to do them in separate statements, itβs not really what direction you are going. Which path is more efficient will depend on the number of concatenations of the sizes of the string involved, and what order they are combined. If you really believe that part of the code should be a bottleneck, profile or compare it in both directions.
Peter Dec 01 '09 at 12:12 2009-12-01 12:12
source share