for( int i = 0; i < lines; i++ ) {
std::unique_ptr<BYTE[]> pLine( new BYTE[lineSize] );
//Do stuff
}
Now, pLine is declared inside the loop because it’s only used in the loop body. However, wouldn’t allocating only once outside the loop reduce the amount of allocations performed (avoiding memory fragmentation)?
std::unique_ptr<BYTE[]> pLine( new BYTE[lineSize] );
for( int i = 0; i < lines; i++ ) {
//Do stuff
}
I could believe the compiler would be able to optimize the first version easily if it knew lineSize stays the same throughout iterations; but it does change throughout function calls, so I can’t make it a constant.
I also think micro optimizations like this should be avoided until a performance problem is detected, so I guess I would stick with the first version. What do you guys think?
The question is really what is in the
//do StuffI would assume you are allocating the memory inside the loop to
unique_ptrbecause somewhere in the//Do stuffsection you are passing ownership of that memory to another object.This if you try and do this:
The first time around the loop ownership is transfered and now
pLinecontains a NULL pointer for the second a subsequent iteration.If you are not transfering ownership then you are probably using the completely wrong method for memory management and a vector is probably a better idea.
The advantage of putting it inside the loop it is re-initialized so all members are zero on every iteration of the loop. If the
//Do Stuffis affected by the state of thepLinethen it may be incorrect to move it outside the loop (without also doing some more work to make sure the state ofpLineis correct after each iteration.