First of all, what is literal constant ?
A literal constant is the representation of a value of a string in the source code, eg
"isto é uma constante literal"
Another example:
var str = "foo";
In this example str is a string and "foo"
In our day-to-day life we do not need to point out this difference, but when we talk about performance over strings it is crucial to differentiate. Because literal constants are values that are present directly in the source code this gives the compiler the opportunity to optimize these operations (such as concatenation at compile time).
Operator +
"A temperatura em " + cidade + " é de " + temperatura;
Pro :
- If you concatenate literal constants the concatenation is performed at compile time.
- It is considered the default.
Contra :
- Unreadable; difficult editing.
string.Concat
string.Concat("A temperatura em ", cidade, " é de ", temperatura);
In terms of performance it is identical to the operator +
(except in case of literal constants).
string.Format
string.Format("A temperatura em {0} é de {1}", cidade, temperatura);
Pro :
- Preferred by many when formatting concatenation (more readable).
- Easy to use a concatenated string multiple times in the original string (just repeat the index).
Contra :
- Little performanceist .
- An execution (not build) error is generated if an invalid number of parameters to be concatenated is passed.
- In a string with many concatenations, it may not be very friendly to have to keep concatenation index numbers.
StringBuilder
new StringBuilder("A temperatura em ").Append(cidade).Append(" é de ").Append(temperatura);
StringBuilder is a class specific to string construction. The big difference from the previous methods is that while the traditional System.String is an immutable object, that is, every operation creates a new string, since StringBuilder is changeable, making it the most pervasive in scenarios involving many operations (read concatenations in loops).
It is important to note that the use in the above example is a case where StringBuilder should not be used.
Considerations
We as programmers like this kind of subject a lot but the reality is that worrying about performance in trivial string concatenations is called micro optimization (notice the bad connotation).
As a general rule, I particularly follow:
- I try to use simple concatenation, via operator
+
.
- If by chance the project I'm working on assumes another way,
string.Concat
for example, I use it. Consistency is important.
- When a large number of concatenations of literal constants is done by the
+
operator. This concatenation will be done at compile time saving precious render cycles.
- When the strings involved are large, multiple operations, loop operations, so when heavy work is done on strings use StringBuilder. Do not use it for trivial work.