1. Should I be worried about declaring a variable inside the loop like this or would the compiler 'optimize' it for me anyways?
( running c++ compiles with default settings )
2. What about other variables declared inside the loop?
Thanks!
Basic types can be allocated on the stack in zero time, so these two snippets have identical performance:
1 2 3 4 5
int i;
/*some loop*/{
i = 0;
// etc.
}
1 2 3 4
/*some loop*/{
int i = 0;
// etc.
}
Likewise for these:
1 2 3 4 5
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
// etc.
}
}
1 2 3 4 5 6
int i, j;
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
// etc.
}
}
In the general case, the same does not hold true for objects. A class may define arbitrarily complex constructors. For example, a constructor might open a TCP connection and get some info from a web server, which may take an unknown amount of time. You need to decide on a case-by-case basis when and where to allocate an object, taking into account the things its constructor and destructor do.