问题描述
.NET提供了四个非常相似的版本 String.Format(...)
(不包括使用 IFormatProvider $ b
格式(字符串,对象)
取代一个或者格式化(字符串,对象,对象)
$ b $指定字符串中的更多格式项目与指定对象的字符串表示形式b用两个指定对象的字符串表示替换指定字符串中的格式项。
格式(字符串,对象,对象,对象)
用三个指定对象的字符串表示替换指定字符串中的格式项。
Format(String,Object [])
用指定字符串中的对应对象的字符串表示替换指定字符串中的格式项指定的数组。为什么不用一个(params)object []
参数?对于具有固定数量的参数(1,2和3)的独立方法,性能增益是否会有所提高?
据推测,对现实世界中的string.Format的大多数调用都有1-3个参数。
这可能是早期实现.NET框架的遗留问题。如果你看格式(字符串,对象),格式(字符串,对象,对象)等方法的实现,你会看到他们都调用格式(IFormatProvider,字符串,对象[])。所以,绝对没有任何性能优势(如果你的构建是在调试模式下运行的话,那么调用对象重载的效率会更低,而不是你可以测量的)。
我能想到的唯一技术原因是这些重载对于不支持params参数的语言是有用的。在这种情况下,程序员仍然可以调用String.Format(Hello {0},world),而不是强制他们创建一个临时数组(这是参数建议编译器要做的)。这也解释了为什么只有3个对象重载:它们覆盖所有String.Format调用的99%。使用反射器或者过期的Rotor代码库。
>.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.
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.
这篇关于为什么string.Format有几种口味?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!