Is it more efficient to preallocate a vector?

后端 未结 3 1979
野的像风
野的像风 2020-12-13 17:54

In C++ Primer fourth edition, by Stanley B.Lippman, Josee Lajoie and Barbara E. Moo it states:

Because vectors grow efficiently, it is usually best to

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 18:47

    It depends.

    If you don't know what the final size will be, then let the vector allocate using its allocation scheme (usually doubles each time, or somewhere around there). This way you avoid reallocating for every single element:

    std::vector v;
    
    // good:
    for (/* populate v */) // unknown number of iterations
    {
        v.push_back(i); // possible reallocation, but not often
    }
    
    // bad:
    for (/* populate v */) // unknown number of iterations
    {
        v.reserve(v.size() + 1); // definite reallocation, every time
        v.push_back(i); // (no reallocation)
    }
    

    But if you know ahead of time you won't be reallocating, then preallocate:

    std::vector v;
    
    // good:
    v.reserve(10); 
    for (/* populate v */) // only 10 iterations (for example)
    {
        v.push_back(i); // no reallocations
    }
    
    // not bad, but not the best:
    for (/* populate v */) // only 10 iterations (for example)
    {
        v.push_back(i); // possible reallocation, but not often (but more than needed!)
    }
    

提交回复
热议问题