I am doing a log
in .Net which before and after each process will fill a string
with the message:
"proceso x realizado \n"
"proceso y saltado \n" //porque o se realiza x o y
"proceso a fallo al sumar \n"
"proceso n [...] \n"
Each message is added to string
after each process with all the messages it has.
As it appears in the title there are several ways to create one string
of this type.
To which my question is, which of the ways to create a string
is the one that consumes less resources or is more efficient.
It should be noted that the string
ending will have at least 25 lines
For the C# case :
String.Format
internally it usesStringBuilder
:operator
+
becomesString.Concat
When we have this code example:
When compiled it becomes:
The official documentation says:
Therefore:
(Now this answer from samjudson makes sense , where he mentions that the first execution and the order matter and will always take longer)
In summary
It depends on the objective of your test, since at the end of the day the format you give to your
String
also consumes resources, since adding a simple string is not the same as adding a string that has a specific format (in this case it would beStringBuilder.Append()
againstStringBuilder.AppendFormat()
) . Some people base the technique to use according to the number of elements they use at the moment . Like aStringBuilder
has much more functionality than just concatenation.Which one should you choose? The answer is it depends. For your exposed case I suggest using
String.Concat
, for more detailed cases the best would beStringBuilder
.References:
The most efficient way to create a character string from the concatenation of other strings is using the class
StringBuilder
, whose objective, as its name indicates, is the construction of objectsString
.