Why does string.Format come in several flavors?

2019-07-17 06:04发布

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

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-17 06:28

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-17 06:50

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.

查看更多
登录 后发表回答