17

Are there differences between these examples? Which should I use in which case?

var str1 = "abc" + dynamicString + dynamicString2;

var str2 = String.Format("abc{0}{1}", dynamicString, dynamicString2);

var str3 = new StringBuilder("abc").
    Append(dynamicString).
    Append(dynamicString2).
    ToString();

var str4 = String.Concat("abc", dynamicString, dynamicString2);

There are similar questions:

This question is asking about what happens in each case, what will be the real output of those examples? What are the differences about them? Where should I use them in which case?

Community
  • 1
  • 1
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 3
    The `+` operator on strings is mapped to `String.Concat` according to the C# specification, by the way. – Mark Rushakoff Jun 23 '10 at 16:07
  • 2
    People, this is not duplicated, I don't care which one is more efficient. – BrunoLM Jun 23 '10 at 18:17
  • 1
    Looks pretty duplicated to me. Certainly many of the answers to the older question would be relevant to this one. And that's not the only dupe either - there are a ton of questions on string concatenation in .NET. But maybe some people will disagree and vote to reopen - that's up to them. – Aaronaught Jun 23 '10 at 18:25
  • "Which should I use in which case" is asked and answered in the other question. – George Stocker Jun 23 '10 at 19:03
  • 1
    @George, the emphasis in the other question (and the answers) is totally on speed. The accepted answer there is awful. – H H Jun 23 '10 at 20:38
  • @BrunoLM Just because you don't agree that it's a duplicate doesn't mean you can remove something the Community User put in there to show that has been closed as a duplicate. – George Stocker Jun 23 '10 at 20:50
  • @George Stocker, lucky there was enough time to get good posts, I could get the answer I was looking for. If it was closed I would be unable to have an answer, I would have to post it again? Or I would have no right to get an answer? Should I post my question as an answer on the "related" question? – BrunoLM Jun 23 '10 at 22:55
  • @Bruno - I think you did the right thing but just remember that we all have to work together to make sure we don't frustrate everyone, including the overzealous question closers. – ChaosPandion Jun 24 '10 at 00:19
  • 2
    @Bruno to answer your question, see: http://stackoverflow.com/questions/2607985/difference-in-string-concatenation-performance and http://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c In fact, that second question actually answers your question in the question. Yes, your question has been asked before, ad infinitum. – George Stocker Jun 24 '10 at 01:30
  • @George Stocker, the question pointed as a exact duplicate doesn't have anything to do with my question. The other one you pointed answers one of my examples only. – BrunoLM Jun 24 '10 at 01:40
  • 1
    @George, it probably is a duplicate but not of the 2 questions you have come up with. The OP here has expressly stated this is not about speed. The other 2 are only about efficiency. – H H Jun 24 '10 at 11:07
  • @Henk: What else **is** there other than speed/efficiency? That's the only meaningful distinction. Saying "this is not about speed" or "I don't care which one is more efficient" only serves to make the question *more vague*. Even the answer you submitted basically revolves around performance - "use the simple version, except when you shouldn't because it's not efficient." All of the ground that's covered in this question has already been covered in the dupes. – Aaronaught Jun 24 '10 at 17:33
  • @Aeronaught: the message is thin but it's there: don't use `string.Concat(firstName, " ", lastName);` I've even seen StringBuilder used for such purposes. And that is partly the fault of 'good advice' as in those other questions. – H H Jun 24 '10 at 17:56

10 Answers10

16

As long as you are not deailing with very many (100+) strings or with very large (Length > 10000) strings, the only criterion is readability.

For problems of this size, use the +. That + overload was added to the string class for readability.

Use string.Format() for more complicated compositions and when substitutions or formatting are required.

Use a StringBuilder when combining many pieces (hundreds or more) or very large pieces (length >> 1000). StringBuilder has no readability features, it's just there for performance.

Ether
  • 53,118
  • 13
  • 86
  • 159
H H
  • 263,252
  • 30
  • 330
  • 514
  • 1
    It may also be worth considering the size of the strings being concatenated. If you were to say concatenate 10 huge strings it would be worth it to use a `StringBuilder`. – ChaosPandion Jun 23 '10 at 15:05
  • @Chaos: Right, but they would have to be really big and handling those would be a separate topic – H H Jun 23 '10 at 15:11
  • 2
    I just wanted to chime in with a semi-intelligent comment. Helps get me through the day. :) – ChaosPandion Jun 23 '10 at 15:27
  • @Chaos, I got that, and I said you were right. I sometimes come across the notion that 100 chars is 'big' and anything over 1000 chars is 'huge'. In answers, we should add ballpark numbers to such adjectives. My error too, I edited a little. – H H Jun 23 '10 at 18:24
  • 2
    You make a lot of sense. Oftentimes I'll take for granted my general knowledge around other programmers. I will be working harder to be more explicit. Also your answer is way better than the accepted one in the duplicate question. – ChaosPandion Jun 23 '10 at 18:50
8

Gathering information from all the answers it turns out to behave like this:

The + operator is the same as the String.Concat, this could be used on small concatenations outside a loop, can be used on small tasks.

In compilation time, the + operator generate a single string if they are static, while the String.Concat generates the expression str = str1 + str2; even if they are static.

String.Format is the same as StringBuilder.. (example 3) except that the String.Format does a validation of params and instantiate the internal StringBuilder with the length of the parameters.

String.Format should be used when format string is needed, and to concat simple strings.

StringBuilder should be used when you need to concatenate big strings or in a loop.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
5

Use the + operator in your scenario.

I would only use the String.Format() method when you have a mix of variable and static data to hold in your string. For example:

string result=String.Format(
    "Today {0} scored {1} {2} and {3} points against {4}",..);

//looks nicer than
string result = "Today " + playerName + " scored " + goalCount + " " + 
    scoreType + " and " + pointCount + " against " + opposingTeam;

I don't see the point of using a StringBuilder, since you're already dealing with three string literals.

I personally only use Concat when dealing with a String array.

casperOne
  • 73,706
  • 19
  • 184
  • 253
ravibhagw
  • 1,740
  • 17
  • 28
2

My rule of thumb is to use String.Format if you are doing a relatively small amount of concatination (<100) and StringBuilder for times where the concatination is going to be large or is potentially going to be large. I use String.Join if I have an array and there isn't any formatting needed.

You can also use the Aggregate function in LINQ if you have an enumerable collection: http://msdn.microsoft.com/en-us/library/bb548651.aspx

Jerod Houghtelling
  • 4,783
  • 1
  • 22
  • 30
  • @Xander just pointed out that String.Format uses a StringBuilder beneath the service. If that's true then I guess String.Fromat vs StringBuilder is a horrible comparison. In that case you might be better off doing the concatenation with '+=' if you aren't going to trash memory too bad. – Jerod Houghtelling Jun 23 '10 at 15:46
  • are you Xander's attorney? if someone point towards grand canion and says - Jump.. are you going to jump? – Boppity Bop Jun 23 '10 at 17:12
1

@ Jerod Houghtelling Answer

Actually String.Format uses a StringBuilder behind the scenes (use reflecton on String.Format if you want)

I agree with the following answer in general

Community
  • 1
  • 1
Xander
  • 1,123
  • 9
  • 14
  • Does the `+` operator use StringBuilder as well? – BrunoLM Jun 23 '10 at 16:29
  • what? are you sure? I did test betweem string.format and sb.append and sb kicked arse.... I think your reflector was drunk at that moment – Boppity Bop Jun 23 '10 at 16:41
  • @BrunoLM: No, a string is immutable, so when you use the + operator, you actually receive a new string instance. – JohnForDummies Jun 23 '10 at 16:43
  • 2
    @Bobb it actually creates a `new StringBuilder`, append the strings, apply the `format` and return the sb.ToString() – BrunoLM Jun 23 '10 at 16:55
  • @BrunoLM - Yes that is the case, String.Format is doing more work hence why its a little slower than using StringBuilder directly. – Xander Jun 28 '10 at 13:01
1

@Xander. I believe you man. However my code shows sb is faster than string.format.

Beat this:

Stopwatch sw = new Stopwatch();
sw.Start();

for (int i = 0; i < 10000; i++)
{
    string r = string.Format("ABC{0}{1}{2}", i, i-10, 
        "dasdkadlkdjakdljadlkjdlkadjalkdj");
}

sw.Stop();
Console.WriteLine("string.format: " + sw.ElapsedTicks);

sw.Reset();
sw.Start();
for (int i = 0; i < 10000; i++)
{
    StringBuilder sb = new StringBuilder();
    string r = sb.AppendFormat("ABC{0}{1}{2}", i, i - 10,
        "dasdkadlkdjakdljadlkjdlkadjalkdj").ToString();
}

sw.Stop();
Console.WriteLine("AppendFormat: " + sw.ElapsedTicks);
casperOne
  • 73,706
  • 19
  • 184
  • 253
Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
  • I did also comparison a while ago - there is even faster solution -when you create SB once in a class life time and then just use sb.Clear before sb.AppendFormat. – Boppity Bop Jun 23 '10 at 17:14
  • 2
    The only difference between them is that `String.Format` instantiate the StringBuilder like this `StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));` and has a parameter validation. That might be the cause of the small difference. – BrunoLM Jun 23 '10 at 17:44
  • Also - use StartNew() rather than reset/start. – Joel Coehoorn Jun 23 '10 at 18:10
  • 1
    @Bruno - if you do few millions operations a day like that - believe me - I do - the difference is not small. – Boppity Bop Jun 23 '10 at 19:27
  • Yes, I agreed. But a situation like that is unlikely. But anyway, using directly StringBuilder is faster than String.Format, there is no doubt. – BrunoLM Jun 24 '10 at 02:34
0

It's important to understand that strings are immutable, they don't change. So ANY time that you change, add, modify, or whatever a string - it is going to create a new 'version' of the string in memory, then give the old version up for garbage collection. So something like this:

string output = firstName.ToUpper().ToLower() + "test";

This is going to create a string (for output), then create THREE other strings in memory (one for: ToUpper(), ToLower()'s output, and then one for the concatenation of "test").

So unless you use StringBuilder or string.Format, anything else you do is going to create extra instances of your string in memory. This is of course an issue inside of a loop where you could end up with hundreds or thousands of extra strings. Hope that helps

Robert Seder
  • 1,390
  • 1
  • 9
  • 19
0

It is important to remember that strings do not behave like regular objets. Take the following code:

string s3 = "Hello ";
string s3 += "World";

This piece of code will create a new string on the heap and place "Hello" into it. Your string object on the stack will then point to it (just like a regular object).

Line 2 will then creatre a second string on the heap "Hello World" and point the object on the stack to it. The initial stack allocation still stands until the garbage collector is called.

So....if you have a load of these calls before the garbage collector is called you could be wasting a lot of memory.

Shane
  • 875
  • 1
  • 6
  • 24
0

I see that nobody know this method:

string Color = "red";
Console.WriteLine($"The apple is {Color}");
Marco Concas
  • 1,665
  • 20
  • 25
-1
var str3 = new StringBuilder
    .AppendFormat("abc{0}{1}", dynamicString, dynamicString2).ToString(); 

the code above is the fastest. so use if you want it fast. use anything else if you dont care.

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
  • 2
    String.Format() uses a StringBuilder behind the scenes, so this is no better. – Joel Coehoorn Jun 23 '10 at 18:09
  • @JoelCoehoorn thanks a lot for down vote mate.. i know its too much to read before comment and down vote.. my answer is `StringBuilder`. but you are the mage of the unexisting horde of SO.. you dont care.. – Boppity Bop Dec 01 '15 at 09:27
  • It's not my downvote, but as this code shouldn't even compile (missing parens for the StringBuilder constructor) I'm not surprised to see one. – Joel Coehoorn Dec 01 '15 at 14:47