Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation Best Practices

Trying to determine if it's a better practice to use string.Format in place of concatenating strings and if so, why is this? Also, are their advantages/disadvantages to one or the other that I should be aware of?

This:

string foo = "I" + " am " + " a " + " string.";

or:

string bar = string.Format("{0} am a {1}.", "I", "string");

Obviously oversimplified examples, just wanting to be clear.

like image 473
Volearix Avatar asked Nov 27 '13 17:11

Volearix


People also ask

What is the most efficient way to concatenate many strings together?

If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.


2 Answers

The "best practice" should be the thing that makes your code the most readable and maintanable. The performance difference between concatenating strings versus using string.Format versus using a StringBuilder is so small that it's essentially irrelevant.

like image 149
Daniel Mann Avatar answered Oct 11 '22 03:10

Daniel Mann


Assuming the first method was not optimized at compile time, because strings are immutable it will create many intermediate strings. It'll work from left to right so there will first be "I am ", then "I am a ", and finally "I am a string." which is stored in foo.

String.format will not make intermediate strings. To my understanding it does all the manipulation in a char[] which is then made immutable by being made a String.

like image 44
Corey Ogburn Avatar answered Oct 11 '22 03:10

Corey Ogburn