Why is calling vector.reserve(required + 1) faster than vector.reserve(required)?

I made the following modification to the program:

size_t a = getenv("A") ? 1 : 0;

void f(std::vector<Class> const & values) {
    ...
    container.reserve(values.size() + a);
    ...
}

Now the performance is same (fast) regardless if a is 0 or 1. The conclusion must be that the reservation of an extra item has no performance impact (which was assumed in the question). Also other small changes to the source code or compiler flags toggles the performance between fast and slow, so it looks like the code optimizer just has better luck in some cases than in others.

The following implementation of f() triggers the opposite behaviour with same compiler flags, thus it is fast when exact size is reserved and slow when an extra item is reserved:

template<typename Container>
void f(std::vector<Class> const & values) {
    Container container;
    container.reserve(values.size());
    for (auto it = values.begin(); it != values.end(); ++it) {
        add(container, *it);
    }
    insert_to_file(container);
}

Leave a Comment