SYSK 196: Is there a performance hit and CPU spike when concatenating literal strings?


For example, is doing something like the code snippet below (done for readability) falls into the “bad practices” category?


string x = “<root>” +


             <items>” +


               <item>” +


                  <name>xyz</name>”


               </item>” +


             </items>” +


           “</root>”;


 


The answer is – no!  The complier is smart enough to create one large string.


 


Of course, executing


            string x = “xyz ” + myVar + ” 123″;


is a totally different story…  Do use string.Format or StringBuilder instead in such cases, e.g.


            string x = string.Format(“xyz %1 123”, myVar);


 

Comments (5)

  1. timheuer says:

    hmmm…i disagree, see http://channel9.msdn.com/ShowPost.aspx?PostID=216980 for metrics on why it shouldn’t be considered a good practice — there is a perf difference.

  2. Eric Newton says:

    Actually the compiler takes the second statement and builds it as a string.Concat as well:

    string xyz = "xyz" + someVar + "zyx";

    gets converted by the compiler into:

    string xyz = string.Concat("xyz",someVar,"zyx");

    HOWEVER, multiple concats will cost you:

    string xyz = "xyz";

    xyz += someVar;

    xyz += "zyx";

    In the previous code, there are 2 string re-allocations, whereas all the other examples, only 1 string is allocated.

  3. RGabo says:

    String.Format likes {0} more than %1.. Do you miss the good old C++ printf days..? I don’t.. 🙂