String concatenation with or without .ToString()?

前端 未结 5 1757
生来不讨喜
生来不讨喜 2020-12-16 23:40

I have a statement where a string is assigned in the following manner:

for (int i = 0; i < x; i++) 
{
    Foo.MyStringProperty = \"Bar_\" + i.ToString();
         


        
5条回答
  •  轮回少年
    2020-12-17 00:22

    As already mentioned by Jon Skeet, the point about boxing is very important!

    If you use explicitly ToString() there is no boxing, which means that no object-box is created around i. The object box around i has to be thrown away later on by the Garbage Collector, causing a performance penalty.

    If you are doing it only a few times in your program it does not matter, but if you are boxing very often, you should go for the ToString() version.

提交回复
热议问题