Skip to content

Conversation

@Dushistov
Copy link
Contributor

std::vector is not very well suited for static, constant arrays.
Since creating it from a std::initializer_list requires memory allocation,
modern C++ compilers miss out on many optimizations.
In particular, compilers are forced to insert a call to a global
atomic variable and a bunch of code for initialization of std::vector.
Plus access to heap memory cause cache misses.
For example for this function:

bool f(const int *arr, int x)
{
    static std::vector<Foo> const values = {A, B, C};
    for (auto v : values) {
        if (arr[static_cast<size_t>(v)] == x)
            return true;
    }
    return false;
}

compiler generates ~60 instructions (gcc 10.2 -O3 -march=native),
if replace std::vector with std::array the result code contains only 9 instructions.

`std::vector` is not very well suited for static, constant arrays.
Since creating it from a list requires memory allocation,
modern C++ compilers miss out on many optimizations.
In particular, compilers are forced to insert a call to a global
atomic variable and a bunch of code for initialization at the place of
its use. Plus access to heap memory cause cache misses
For example for this function:
bool f(const int *arr, int x)
{
    static std::vector<Foo> const values = {A, B, C};

    for (auto v : values) {
        if (arr[static_cast<size_t>(v)] == x)
            return true;
    }
    return false;
}

compiler generates ~60 instructions (gcc 10.2 -O3 -march=native),
if replace `std::vector` with `std::array` the result code contains only 9 instructions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant