views:

171

answers:

2

.NET provides four very similar versions of String.Format(...) (excluding the one that takes an IFormatProvider argument):

Format(String, Object)
Replaces one or more format items in a specified string with the string representation of a specified object.
Format(String, Object, Object)
Replaces the format item in a specified string with the string representations of two specified objects. Format(String, Object, Object, Object)
Replaces the format items in a specified string with the string representation of three specified objects. Format(String, Object[])
Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

Why not have just the one with a (params) object[] argument? Is there a performance gain for separate methods with a fixed number of parameters (1, 2 and 3)?
Presumably, most calls to string.Format in the real world have 1-3 parameters.

+1  A: 

Yes. There is a performance difference associated with building an array and passing that one instead of simply passing individual arguments on stack. Also, since .NET is designed to support many languages, they might have been doing this to support normal String.Format syntax for some possible hypothetical language that didn't support automatically packing params array parameters.

Mehrdad Afshari
If performance is an issue, why even use String.Format?
Zyphrax
Well. If you were to write the `String.Format` function yourself, you might have chosen not to care but Microsoft builds a framework used in many many situations. It makes sense for them to take the most out of every processor cycle.
Mehrdad Afshari
+4  A: 

It's probably a relic from an early implementation of the .NET Framework; if you'd look* at the implementations of the Format(string, object), Format(string, object, object), etc. methods, you'll see that they all call Format(IFormatProvider, string, object[]). So there's absolutely no performance benefit whatsoever (if your build is run in debug mode, it's even less effecient to call the object overloads--not that you'll be able to measure it).

The only thechnical reason I can think of, is that these overloads are useful for languages that don't support params arguments. In that case, programmers can still call String.Format("Hello {0}", "world"), rather that forcing them to create a temp array (which is what params arguments suggest the compiler to do). Which also explains why there are just 3 object overloads: these cover 99% of all String.Format calls.

*) Using Reflector or the dated Rotor codebase.

Ruben