for(int i = 0; i < 10; ++i){
int x = 0;
//stuff
}
vs
int x;
for(int i = 0; i < 10; ++i){
x = 0;
//stuff
}
I'm concerned about performance and memory usage.
for(int i = 0; i < 10; ++i){
int x = 0;
//stuff
}
vs
int x;
for(int i = 0; i < 10; ++i){
x = 0;
//stuff
}
I'm concerned about performance and memory usage.
Modern compilers do a lot of optimizations under the hood. You might feel that the first example is not performant because it creates x
for each iteration, however it is not the case.
First example: https://godbolt.org/z/T2bsvG
Second example: https://godbolt.org/z/sRNjcV
If you compile the assembly, you can see they are identical.
Should I be concerned about redundant declarations?
Usually, no.
I'm concerned about performance and memory usage.
You can compare the assembly of one way to the other, and may find that the resulting program is identical. If not, then you can measure the performance, if that is your concern. But I suspect that there is probably no difference in performance in practice.
Limiting the scope of variables to be as narrow as is sufficient is usually the best practice for making the program easy to understand.
If you're asking this in terms of scoping then yes there are times (especially when dealing with smart pointers) when it is important whether to have a variable live in the scope where it is used or have it live outside that scope.
As you may know, the reason for having smart pointers in C++ is to aid in resource management so that freeing heap memory does not have to be a chore.
See: What is a smart pointer and when should I use one?
An example could be if you had smart pointer that is used to encapsulate a reference to a database connection and you have to call a function that uses this connection. It would really matter where that smart pointer lives because if it lives inside the function, then the connection would be opened and closed every time this function is called which could cost you precious lost milliseconds and depending on the frequency of the calls, it could end up costing several hours in lost time. However, if it lives outside the function then the database is already opened whenever the function is called and there is no need to open it again.
My rule of thumb is to try as much as possible to delay creating any variables up until the point where it is needed. Undoubtedly, there are cases when it doesn't really matter such as the case you have above, and there are people who like the aesthetics of code that declares variables in one place, and then use them.
In terms of performance, rather than int x = 0;
consider MyType x = 0;
where the constructor for MyType
does a lot of work. In that case, creating x
once before entering the loop will do less work than creating x
each time through the loop. However, if the logic of the program requires a new x
each time through the loop, creating a single one before entering the loop will simply be wrong.