AMissico
AMissico

Reputation: 21684

string.format vs + operator for string concatenation

Which is better in respect to performance and memory utilization?

// + Operator
oMessage.Subject = "Agreement, # " + sNumber + ", Name: " + sName;

// String.Format
oMessage.Subject = string.Format("Agreement, # {0}, Name: {1}", sNumber, sName);

My preference is memory utilization. The + operator is used throughout the application. String.Format and StringBuilder is rarely use. I want to reduce the amount of memory fragmentation caused by excessive string allocations.

Upvotes: 1

Views: 484

Answers (1)

Guffa
Guffa

Reputation: 700840

The best option in this specific case is the + operator. The compiler will make a call to String.Concat out of your code:

oMessage.Subject = String.Concat("Agreement, # ", sNumber, ", Name: ",  sName);

The String.Concat will loop through the strings to determine the total length, allocate a string with that length and copy each string into that. It's the most efficient way of concatenating a bunch of strings.


Note: If you are concatenating strings with value types (e.g. integers), you should explicitly convert them to strings. Otherwise they will be boxed, and everything is sent as objects to the String.Concat method:

oMessage.Subject = "Agreement, # ", iNumber.ToString();

Upvotes: 9

Related Questions