It has already been properly said that the best way is to use a single string
in the case presented. It is quick and readable.
But if there is a reason to do the 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 compiler optimization in many cases. But not at all. If all sizes string
the involved ones are not known, there is not so much optimization. In these cases the optimization only transforms the concatenations in the method concat()
. It is certainly better because it avoids unnecessary allocations, but size calculation is still required.
Despite the property SqlCommand.CommandText
be the type string
, I have doubts if it can be so optimized.
If a StringBuilder
may be suitable and have no performance impairment. It may even be faster than a method concat()
of string
. When you know the total size required for all string
s simply, possibly as constant literal, the StringBuilder
is very fast. Internally (.NET Core) the concat()
uses a StringBuilder
optimized, therefore find that the first is faster than the second does not make sense. Of course in cases that have only 4 string
s the concatenation is made in a simpler way without StringBuilder
.
But so far little new has been added to what has already been said in the other answers.
Alternative: Resources
There are cases that to facilitate the work, the text should not be in the code. It should be in an external file, when relevant, or be in Resources. It can be easier to maintain this and is very fast in the second case.
For everything there is the best applied solution. This is a case that facilitated maintenance can be more important than performance. In case you take the Resource performance will not be affected much. And even if it is, it will not create a problem for the application. This concern with performance makes sense for cases of extreme manipulations of strings. 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 have the possibility to change the text easily after the compilation, when you want to give this freedom to the user.
Through the mentioned topic I got to this link (http://yoda.arachsys.com/csharp/stringbuilder.html) with great explanations, as well as you summarized in the answer. The @ solution is very good because I can easily manipulate the code in the BD program and then paste it into the application.
– Joao Paulo