However, when considering the overall performance picture, realize that Simon's second and third examples add uncertainty to your program, both in execution speed and stack usage. When running hard realtime, you may actually want to use global variables instead of having a wildly variable stack.
The bottom line is that you have to understand the ramifications of doing it each of the three suggested ways. Memory leaks, errors, and fragmentation can't happen if you declare everything global and don't use stack or heap allocations. You can, however, mess up if you don't pay careful attention to variable names and where you use each variable.
I have seen a lot of folks with realtime software that hangs or does unexpected things simply because they think that the second and third methods are preferred. They can't even debug their programs properly because of stack overflows, etc. If you are looking for consistent performance, particularly with a lot of variables and a throughput requirement, I would use number one above, but be very careful about naming and using the globals.
And by the way, none of the methods are "harder" on the CPU. It simply does exactly what you tell it to do.
Regards,
- Gary
Hello,
I'm wanting to try and cut down on possible memory error / fragmentation issues in my program. I was wondering which is harder on the CPU? * BTW: The math is meaningless... I'm trying to undersand the difference in how these vailables are declared... Imagine a huge program running all sorts of calcs very fast...
---Example1:---int counter = 0; int a = 0; int b = 0;
int main() {
while (1) {
counter++; a = counter; b = (a + counter); if(counter >= 1000){counter = 0;}
}
}
---Example2:---int counter = 0;
int main() {
while (1) {
counter++; int a = counter; int b = (a + counter); if(counter >= 1000){counter = 0;}
}
}