It has been properly said that the best way is to use a single string
in the case presented. It's fast and legible.
But if there is a reason to do sequential concatenation, it can be used without performance problems. It ends up becoming a single string
at compile time. The only problem is being less readable.
There is optimization of the compiler in many cases. But not at all. If all of the% s sizes involved are not known, there is not so much optimization. In these cases the optimization only transforms the concatenations in the string
method. It is certainly better because it avoids unnecessary allocations, but the size calculation is still needed.
Although the concat()
property is of type SqlCommand.CommandText
, I have doubts if it can be so optimized.
If it is useful a string
may be appropriate and not have a performance impairment. It may even be faster than a method StringBuilder
of concat()
. When you know the total size required for all% s of% s in a simple way, possibly as a constant literal, string
is very fast. Internally string
uses a StringBuilder
so you find that the former is faster that the second one does not make sense. Of course, in cases that have only 4% with% s the concatenation is made simpler without concat()
.
But so far little has been added to what has been said in the other answers.
Alternative: Resources
There are cases to make work easier, the text should not be in the code. It should be in an external file, when this is pertinent, or be in Resources . It may be easier to maintain in this and it is very fast in the second case.
For everything there is the best solution applied. This is a case that easier maintenance can be more important than performance. In case of catching the resource the performance will not be much affected either. And even if it is, it will not create problem for the application. This performance concern makes sense for cases of extreme strings manipulations . In the case of file access the performance will obviously be affected by access to mass memory. But it will still not affect the application. Of course this solution should only be chosen when you want to be able to change the text easily after compilation, when you want to give this freedom to the user.