String concatenation with or without .ToString()?

前端 未结 5 1741
生来不讨喜
生来不讨喜 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:17

    I would use .ToString() out of habit and readability, I am sure you will find better performance saving elsewhere.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 00:31

    + concatenation uses String.Concat anyway - String itself doesn't expose a + operator.

    So for example:

    int i = 10;
    string x = "hello" + i;
    

    is compiled into:

    int i = 10;
    object o1 = "hello";
    object o2 = i; // Note boxing
    string x = string.Concat(o1, o2);
    

    Whereas calling ToString directly will avoid boxing and call the Concat(string, string) overload. Therefore the version with the ToString call will be slightly more efficient - but I highly doubt that it'll be significant, and I'd strongly urge you to go with whichever version you feel is more readable.

    0 讨论(0)
  • 2020-12-17 00:34

    Just using string + object forces a call to ToString() on the object - it's equivalent to calling it explicitly.

    0 讨论(0)
  • 2020-12-17 00:34

    ToString is the default method used to write an object. So, if you use "i" or "i.ToString()" is the same thing.

    If you know a little about operator overloading in c++ you can understand how "+" works in this case.

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Text;
    
    
    public class MainClass
    {
        public static void Main()
        {
            int number = 10;
            string msg = "age is " + number + ".";
            msg += " great?";
            Console.WriteLine("msg: {0}", msg);
    
            String s1 = 10 + 5 + ": Two plus three is " + 2 + 3;
            String s2 = 10 + 5 + ": Two plus three is " + (2 + 3);
            Console.WriteLine("s1: {0}", s1);
            Console.WriteLine("s2: {0}", s2);    }
    
    }
    

    Result: msg: age is 10. great?

    s1: 15: Two plus three is 23

    s2: 15: Two plus three is 5

    0 讨论(0)
提交回复
热议问题