Reputation: 83
When I make a function most of the time I make a lot of variables inside of it, just because its easier to debug the code.
Lets say I have this function:
void foo(int value) {
int x = value * 1;
int y = value * 2;
int z = value * 3;
int u = x + 1;
int v = y + 2;
int w = z + 3;
}
This code is fine and its easy to debug (you can see step by step what is happening) but its using a lot of memory (28 bytes considering that each int
is 4 bytes), and it could be optimized in this way:
void foo(int value) {
int u = value * 1 + 1;
int v = value * 2 + 2;
int w = value * 3 + 3;
}
Based on this I have some questions:
Upvotes: 1
Views: 91
Reputation: 31467
Yes. A modern compiler will remove those intermediate variables. Yes. A modern compiler will fold constants and reuse registers and memory locations.
In short; don't worry about stuff at this level, the compiler will fix it. Instead worry about writing readable code and algorithmic improvements and leave the details to the compiler - it's pretty smart these days ;)
Upvotes: 3