我的编译器会忽略无用的代码吗?

2023-12-25

我已经通过网络询问了有关此主题的一些问题,但我没有找到我的问题的任何答案,或者它是对于另一种语言 https://stackoverflow.com/q/30703896/2307070或者它没有完全回答 https://stackoverflow.com/q/10192076/2307070(死代码是not无用的代码)所以这是我的问题:

编译器是否会忽略(显式或非显式)无用的代码?

例如,在这段代码中:

double[] TestRunTime = SomeFunctionThatReturnDoubles;
// A bit of code skipped
int i = 0;
for (int j = 0; j < TestRunTime.Length; j++)
{

}
double prevSpec_OilCons = 0;

for循环会被删除吗?

I use .net4.5 /questions/tagged/.net4.5 and vs2013 /questions/tagged/vs2013


The background is that I maintain a lot of code (that I didn't write) and I was wondering if useless code should be a target or if I could let the compiler take care of that.


Well,你的变量i and prevSpec_OilCons,如果不在任何地方使用,将会被优化掉,但不是你的循环。

因此,如果您的代码如下所示:

static void Main(string[] args)
{
    int[] TestRunTime = { 1, 2, 3 };
    int i = 0;
    for (int j = 0; j < TestRunTime.Length; j++)
    {

    }
    double prevSpec_OilCons = 0;
    Console.WriteLine("Code end");
}

under ILSpy http://ilspy.net/这将是:

private static void Main(string[] args)
{
    int[] TestRunTime = new int[]
    {
        1,
        2,
        3
    };
    for (int i = 0; i < TestRunTime.Length; i++)
    {
    }
    Console.WriteLine("Code end");
}

由于循环有几个语句,例如比较和增量,因此它可以用于实现somewhat短暂的延迟/等待期。 (虽然这样做不是一个好的做法).

考虑下面的循环,它是一个空循环,但执行起来会花费很多时间。

for (long j = 0; j < long.MaxValue; j++)
{

}

你的代码中的循环并不是死代码,就死代码而言,以下是死代码,将被优化掉。

if (false)
{
    Console.Write("Shouldn't be here");
}

该循环甚至不会被 .NET 抖动消除。基于此answer https://stackoverflow.com/a/7288572/961113

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我的编译器会忽略无用的代码吗? 的相关文章

随机推荐