Performance degradation due to default initialisation of elements in standard containers

后端 未结 4 1658
广开言路
广开言路 2020-12-05 13:41

(Yes, I know there is a question with almost the same title, but the answer was not satisfactory, see below)

EDIT Sorry, the original question didn\'t u

4条回答
  •  没有蜡笔的小新
    2020-12-05 14:07

    I'm actually going to suggest in this case to roll your own container or look for alternatives since with the way I see it, your inherent problem is not with standard containers default constructing elements. It's with trying to use a variable-capacity container for one whose capacity can be determined upon construction.

    There is no instance where the standard library needlessly default constructs elements. vector only does so for its fill constructor and resize, both of which are conceptually required for a general-purpose container since the point of those is to resize the container to contain valid elements. Meanwhile it's simple enough to do this:

    T* mem = static_cast(malloc(num * sizeof(T)));
    for (int j=0; j < num; ++j)
         new (mem + j) T(...); // meaningfully construct T
    ...
    for (int j=0; j < num; ++j)
         mem[j].~T();         // destroy T
    free(mem);
    

    ... and then build an exception-safe RAII-conforming container out of the code above. And that's what I suggest in your case since if default construction is wasteful enough to be non-negligible in a fill constructor context to the point where the alternative reserve and push_back or emplace_back is equally inadequate, then chances are that even a container treating its capacity and size as a variable is a non-negligible overhead, at which point you are more than justified to seek out something else, including rolling your own thing from the concept above.

    The standard library is pretty damned efficient for what it does in ways where it's incredibly difficult to match in apples to apples comparisons, but in this case your needs call for oranges rather than apples. And in such cases, it often starts to become easier to just reach for an orange directly rather than trying to transform an apple to become an orange.

提交回复
热议问题