lundi 28 novembre 2022

Reserve 2D std::vector of Widgets

For some legacy code reasons, I have to live with below code

// Header.h

class Widget
{
   // bunch of primitive types 
   // no fancy C++11 ish member functions

};

class BigWidget
{
   std::vector<std::vector<Widget>> w2dlist;
};

// Source.cpp

void someFunction()
{
   // some runtime calculations of numRows and numCols

    w2dlist.reserve(numRows);

    for (auto& r : w2dlilst)
    {
        r.reserve(numCols);
    }
    
    for (int i = 0; i < numRows; i++) 
    {
        w2dlist.emplace_back();   // emplace some default constructed objects
        
        for (int j = 0; j < numCols; j++) 
        {
===>>>            w2dlist[i].emplace_back(); // do the same 
        }
    }
}

I can not change the Widget/BigWidget class with rule of 4/5 members. But the profiler is pointing the line in the inner loop as one of the hotspots.

How can I improve this ?

I have tried below tricks

  1. default construct Widget as Widget{} while emplace'in , the static checker (and eventually runtime) point to stack overflow and crashes the app
  2. default construct/reserve 2D vector in BigWidget constructor, profiler then shifts the hotspot to this operation
  3. Meyer's singleton while emplacin' the Widgets :D , profiler is merciless

Profiler/Compiler : Visual Studio 2019 (C++17)

OS : Windows

Aucun commentaire:

Enregistrer un commentaire