I have the following code in C++ here:
#include <iostream>
int main(int argc, const char * argv[])
{
goto line2;
line1:
std::cout << "line 1";
goto line3;
line2:
std::cout << "line 2";
goto line1;
line3:
std::cout << "line 3";
goto line4;
line4:
std::cout << "Hello, World!\n";
return 0;
}
If I made a larger program of lets say 10,000 lines of code and I decide I am never going to use functions that I write myself, I only use goto
statements. I only use global variables. I am slightly insane in terms of best practices, but its for a very specific purpose. The question is, would this be efficient to jump around with goto
statements? What if I have 1000 goto
labels?
Do the goto
statements translate directly into machine code which tells the computer just to JUMP to a different memory address? Is this a lower cost in the machine to jump around like this when compared with the cost to call a function?
I wish to know as I want to write a very efficient program to do some computations and I need to be very efficient without resorting to Assembly/Machine code.
No need to tell me this is a bad idea in terms of maintenance, understandability of code, best practices, I'm very aware of that, I just wish to have an answer to the question. I don't want any debate between whether its good to use function calls or good to use goto
.
To clarify the question, I am concerned in this case of using goto
s only with a 10,000 line program as to how it would compare with a traditional program using functions. There are multiple ways to compare and contrast between these two programs, for example how would the CPU cache perform. What sort of saving would it give without function calls. Without a call stack, how would this impact on the CPU cache, as CPU caches usually keep the stack close. Would there be therefor a case where it is likely to have a negative performance hit due to the cache not being utilized correctly. What is the actual cost of calling a function as compared to a jump in terms of time efficiency. There's a lot of ways to compare and contrast the two styles of programming in terms of efficiency.