Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c# - Will my compiler ignore useless code?

I've been through a few questions over the network about this subject but I didn't find any answer for my question, or it's for another language or it doesn't answer totally (dead code is not useless code) so here's my question:

Is (explicit or not) useless code ignored by the compiler?

For example, in this code:

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

}
double prevSpec_OilCons = 0;

will the for loop be removed?

I use and


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.

question from:https://stackoverflow.com/questions/31027060/will-my-compiler-ignore-useless-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, your variables i and prevSpec_OilCons, if not used anywhere will be optimized away, but not your loop.

So if your code looks like:

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 it will be:

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");
}

Since the loop has couple of statements, like comparison and increment, it could be used for implementing somewhat short delay/wait period. (although not a good practice to do so).

Consider the following loop, which is an empty loop, but it will take a lot of time to get executed.

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

}

The loop in your code, is not a dead code, as far as dead code is concerned, the following is a dead code, and will be optimized away.

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

The loop, will not even be removed by the .NET jitters. Based on this answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...