https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96088

            Bug ID: 96088
           Summary: Range insertion into unordered_map is less effective
                    than a loop with insertion
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: antoshkka at gmail dot com
  Target Milestone: ---

Consider the function f1:

static constexpr std::initializer_list<std::pair<const char*, int>> lst = {
    {"long_str_for_dynamic_allocating", 1}};

void f1() {
    std::unordered_map<std::string, int> m(1);
    m.insert(lst.begin(), lst.end());
}


It creates a temporary and as a result makes 4 allocations. Meanwhile f2 does
not create a temporary and does aonly 3 allocations:

void f2() {
    std::unordered_map<std::string, int> m(1);
    for (const auto& x : lst) {
        m.insert(x);
    }
}


Godbolt playground: https://godbolt.org/z/VapmBU

Reply via email to