简体   繁体   中英

Is the goto statement slow in c#?

I'm working on a C# .NET application that uses some rather complex scientific formulas on large sets of data (10 million data points on average). Part of what I am doing requires optimizing the formula implementations as best as possible.

I noticed that one formula implementation uses goto, and that made me wonder: is goto slower than other flow control constructs?

is goto slower than other flow control constructs?

No. All the other flow control constructs are basically goto anyway.

The goto instruction in C# is no slower than any other control flow construct. In fact the vast majority of control flow constructs (if, while, for, etc ...) is implemented in terms of goto .

For example:

if (someExpr) { 
  Console.WriteLine("here");
}
Console.WriteLine("there");

Is essentially compiled down to the following

gotoIf !someExpr theLabel;
Console.WriteLine("here");
theLabel:
Console.WriteLine("there");

I noticed that one formula implementation uses goto, and that made me wonder: is goto slower than other flow control constructs?

goto will not be any slower than any other flow control mechanism. It, like most flow control mechanisms get compiled into a br.s (or similar) MSIL instruction. However, there are some situations where goto can be slightly faster. They are mostly limited to situations involving the use of break and continue inside nested loops. Consider the following code.

bool condition = false;
for (int i = 0; i < BigNumber; i++)
{
    for (int j = 0; j < i; j++)
    {
        for (int k = 0; k < j; k++)
        {
            condition = Evaluate(i, j, k);
            if (condition)
            {
              // break out of everything
            }
        }
    }
}

There are different ways you could you break out of the entire thing. Here is one method.

bool condition = false;
for (int i = 0; i < BigNumber; i++)
{
    for (int j = 0; j < i; j++)
    {
        for (int k = 0; k < j; k++)
        {
            condition = Evaluate(i, j, k);
            if (condition) break;
        }
        if (condition) break;
    }
    if (condition) break;
}

The problem is that each loop must check the condition flag. We could refactor this with a goto to make it slightly more efficient and a bit more elegant to boot.

for (int i = 0; i < BigNumber; i++)
{
    for (int j = 0; j < i; j++)
    {
        for (int k = 0; k < j; k++)
        {
            if (Evaluate(i, j, k)) goto BAILOUT;
        }
    }
}
BAILOUT:

if s和for由编译器在内部转换为goto ,则它们的速度不会比goto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM