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

Commits on Mar 26, 2021

  1. std::vector -> std::array for constant

    `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.
    Dushistov committed Mar 26, 2021
    Configuration menu
    Copy the full SHA
    a9f2bd9 View commit details
    Browse the repository at this point in the history