What are the performance benefits or penalties of using goto
with a modern C++ compiler?
I am writing a C++ code generator and use of goto
will make it easier to write. No one will touch the resulting C++ files so don't get all "goto is bad" on me. As a benefit, they save the use of temporary variables.
I was wondering, from a purely compiler optimization perspective, the result that goto has on the compiler's optimizer? Does it make code faster, slower, or generally no change in performance compared to using temporaries / flags.
The part of a compiler that would be affected works with a flow graph. The syntax you use to create a particular flow graph will normally be irrelevant as long as you're writing strictly portable code--if you create something like a while
loop using a goto
instead of an actual while
statement, it's not going to produce the same flow graph as if you used the syntax for a while
loop. Using non-portable code, however, modern compilers allow you to add annotations to loops to predict whether they'll be taken or not. Depending on the compiler, you may or may not be able to duplicate that extra information using a goto
(but most that have annotation for loops also have annotation for if
statements, so a likely taken
or likely not taken
on the if
controlling a goto
would generally have the same effect as a similar annotation on the corresponding loop).
It is possible, however, to produce a flow graph with goto
s that couldn't be produced by any normal flow control statements (loops, switch, etc.), such conditionally jumping directly into the middle of a loop, depending on the value in a global. In such a case, you may produce an irreducible flow graph, and when/if you do, that will often limit the ability of the compiler to optimize the code.
In other words, if (for example) you took code that was written with normal for
, while
, switch
, etc., and converted it to use goto
in every case, but retained the same structure, almost any reasonably modern compiler could probably produce essentially identical code either way. If, however, you use goto
s to produce the mess of spaghetti like some of the FORTRAN I had to look at decades ago, then the compiler probably won't be able to do much with it.