String concatenation with or without .ToString()?
Asked Answered
A

5

8

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();
    /* ... */
}

Are there any performance differences between i.ToString() or just plain i, as both are just converted to the (culture invariant?) string equivalent?

I am well aware of the existence of String.Concat(), String.Format, StringBuilder, etc., but for the sake of this case, lets assume I may only use + concatenation.

Thanks in advance.

Ananna answered 29/12, 2009 at 14:1 Comment(2)
can't you make a testapplication? Let it loop for 10.000 times, measure the time and you know the answer.Waites
Caveat: ToString() uses the current culture. If you want culture-independent conversion you would have to use ToString(CultureInfo.InvariantCulture) (This is more important when dealing with floating point numbers than with integers).Skat
K
26

+ 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.

Koons answered 29/12, 2009 at 14:10 Comment(3)
Thanks, very clear answer. Though I'd be tempted to accept divo's comment if it were an answer instead, because of his caveat about the culture info.Ananna
In my testing the boxing and unboxing of a value type when NOT using the ToString method causes about a 2.5% performance hit.Egin
Interesting. I thought maybe the C# compiler would generate the same IL in the two situations, but you're right, it doesn't (not with C# 5 either). The situation with a reference type is a little different. Here the code "hello" + obj will not throw even if obj is a null reference. But "hello" + obj.ToString() will throw if obj is null, of course. However, even with reference types the style with explicit .ToString() could theoretically be faster (when obj is non-null) because it uses the Concat(string, string) overload instead of the Concat(object, object) overload.Hestia
R
6

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

Reft answered 29/12, 2009 at 14:4 Comment(1)
@Aviad: There's a difference in timing, however - which affects whether the value is boxed or not.Koons
F
2

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

Falstaffian answered 29/12, 2009 at 14:14 Comment(0)
P
0

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

Partisan answered 29/12, 2009 at 14:8 Comment(0)
S
0

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.

Simpleton answered 11/3, 2013 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.