Vector declared in loop (EXPENSIVE_VECTOR_IN_LOOP)
R2026bAllocating and deallocating vectors in a loop results in inefficient code
Since R2026b
Description
This defect occurs when you declare a std::vector inside a loop body.
Each loop iteration allocates and deallocates memory for the vector, which degrades
performance.
Polyspace®
Bug Finder™ flags std::vector declarations inside for,
while, and do-while loops, including nested loops. The
checker does not flag vectors that are move-initialized inside the loop because moving avoids
the allocation overhead.
Risk
Declaring a std::vector inside a loop causes repeated heap
allocations and deallocations. These operations are expensive compared to reusing an
existing vector:
Each iteration invokes the allocator to reserve memory and the destructor to release it.
In performance-critical loops, the cumulative cost of these allocations can significantly slow execution.
The repeated allocations can also cause heap fragmentation.
Fix
To fix this defect, move the vector declaration outside the loop and call
clear() at the beginning of each iteration:
Declare the
std::vectorbefore the loop.Replace the in-loop declaration with a call to
vec.clear()orvec.assign(...)to reset the vector contents without deallocating memory.
Examples
Result Information
| Group: PERFORMANCE |
| Language: C++ |
| Impact: Medium |
Command-Line Syntax:
EXPENSIVE_VECTOR_IN_LOOP |
Version History
Introduced in R2026b