Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::vector -> std::array for constant #14154

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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