C#编译器不会优化不必要的转换 [英] C# compiler doesn’t optimize unnecessary casts

查看:107
本文介绍了C#编译器不会优化不必要的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天后,在这里写下这个问题的答案在溢出我有一个惊讶的C#编译器,谁没有做我期望它做的。查看以下代码片段:

A few days back, while writing an answer for this question here on overflow I got a bit surprised by the C# compiler, who wasn’t doing what I expected it to do. Look at the following to code snippets:

第一个:

object[] array = new object[1];

for (int i = 0; i < 100000; i++)
{
    ICollection<object> col = (ICollection<object>)array;
    col.Contains(null);
}

其次:

object[] array = new object[1];

for (int i = 0; i < 100000; i++)
{
    ICollection<object> col = array;
    col.Contains(null);
}

两个代码段之间的唯一区别是转换为ICollection< object >。因为object []显式地实现了ICollection< object>接口,所以我期望这两个片段编译到同一个IL,因此是相同的。然而,当对他们进行性能测试时,我注意到后者的速度是前者的6倍。

The only difference in code between the two snippets is the cast to ICollection<object>. Because object[] implements the ICollection<object> interface explicitly, I expected the two snippets to compile down to the same IL and be therefore identical. However, when running performance tests on them, I noticed the latter to be about 6 times as fast as the former.

在比较两个片段的IL之后,我注意到除了第一个片段中的 castclass IL指令,两种方法都是相同的。

After comparing the IL from both snippets, I noticed the both methods were identical, except for a castclass IL instruction in the first snippet.

我惊讶于这一点我现在想知道为什么C#在这里聪明。事情从来没有像它看起来那么简单,所以为什么C#编译器有点幼稚?

Surprised by this I now wonder why the C# compiler isn’t ‘smart’ here. Things are never as simple as it seems, so why is the C# compiler a bit naïve here?

推荐答案

在优化器中发现了一个小错误。有各种特殊情况的代码在那里的数组。感谢您提请我注意。

My guess is that you have discovered a minor bug in the optimizer. There is all kinds of special-case code in there for arrays. Thanks for bringing it to my attention.

这篇关于C#编译器不会优化不必要的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆