C++: Optimizing speed with vector/array?

前端 未结 8 1793
半阙折子戏
半阙折子戏 2021-01-02 00:51

I have a nested for-loop structure and right now I am re-declaring the vector at the start of each iteration:

void function (n1,n2,bound,etc){

    for (int          


        
8条回答
  •  猫巷女王i
    2021-01-02 01:31

    I have a clear preference for small scopes (i.e. declaring the variable in the innermost loop if it’s only used there) but for large sizes this could cause a lot of allocations.

    So if this loop is a performance problem, try declaring the variable outside the loop and merely clearing it inside the loop – however, this is only advantageous if the (reserved) size of the vector stays identical. If you are resizing the vector, then you get reallocations anyway.

    Don’t use a raw array – it doesn’t give you any advantage, and only trouble.

提交回复
热议问题