装箱和拆箱的的String.Format(...)...是以下合理化?String、Format

2023-09-04 07:08:42 作者:装逼文艺范儿

我在做一些阅读有关装箱/拆箱,而且事实证明,如果你做一个普​​通的的String.Format(),你有一个值类型的列表对 [对象] 参数,它会引起装箱操作。举例来说,如果你想打印出一个整数的值,做的String.Format(我的值是{0},设为myVal),它会坚持你的设为myVal INT 在一个盒子里,然后运行的ToString 功能就可以了。

浏览周围,I发现这篇文章。

看来你能避免装箱损失只需通过执行的ToString 上的值类型上交给它的的String.Format函数之前:的String.Format(我的值是{0},myVal.ToString())

这是真的吗?我倾向于相信笔者的 证据。 如果这是真的,为什么不编译器只是做到这一点 为你?也许这是自2006年以来改变?有谁知道? (我没有时间/体验做全IL分析) 解决方案

编译器不适合你,因为的String.Format 做到这一点需要一个 params对象[] 。拳击是因为转换到对象

我不认为编译器倾向于特殊情况的方法,这样就不会在情况下,删除拳击这样的。

是在许多情况下,这是事实,编译器不会做拳击,如果你调用的ToString()第一。如果使用来自对象的实施,我认为它仍然有框。

最后的的String.Format 解析格式字符串本身将是比任何装箱操作慢得多,所以开销可以忽略不计。

I was doing some reading regarding boxing/unboxing, and it turns out that if you do an ordinary String.Format() where you have a value type in your list of object[] arguments, it will cause a boxing operation. For instance, if you're trying to print out the value of an integer and do string.Format("My value is {0}",myVal), it will stick your myVal int in a box and run the ToString function on it.

Browsing around, I found this article.

装箱与拆箱的理解

It appears you can avoid the boxing penalty simply by doing the .ToString on the value type before handing it on to the string.Format function: string.Format("My value is {0}",myVal.ToString())

Is this really true? I'm inclined to believe the author's evidence. If this is true, why doesn't the compiler simply do this for you? Maybe it's changed since 2006? Does anybody know? (I don't have the time/experience to do the whole IL analysis)

解决方案

The compiler doesn't do this for you because string.Format takes a params Object[]. The boxing happens because of the conversion to Object.

I don't think the compiler tends to special case methods, so it won't remove boxing in cases like this.

Yes in many cases it is true that the compiler won't do boxing if you call ToString() first. If it uses the implementation from Object I think it would still have to box.

Ultimately the string.Format parsing of the format string itself is going to be much slower than any boxing operation, so the overhead is negligible.