I am trying to write an efficient multistep solver in C++ using the Eigen library. To do so, I need a few variables that keep track of the history. One of them is of type Eigen::VectorX<Eigen::Matrix<double, 9, 10>> DD which is resized to 10000 somewhere in my initialization code.
Even though I know the size of DD at compile time, I need to allocate it on the heap because DD is too large for the stack (at least that's what Visual Studio 2022 tells me).
And here things are getting confusing to me. I'll try to explain why:
You may have noticed that
DDis aVectorXof size 10000 living on the heap. Its elements are of typeMatrix<double, 9, 10>, hence living on the stack (?). Writing this text already sounds wrong to me. Is it possible to have an object that is allocated both on heap and stack? Or is the compiler moving everything on the heap?If allocating both on heap and stack is possible: does it influence the performance when reading from the
DD?I thought I replace
Matrix<double, 9, 10>byMatrixXdand give it a try. Well, it works but things are slown down by 15-20%. So, somehow I think this question gives an answer to my first and second question but I am really not convinced yet.If I could replace
VectorXbyVector<..., 10000>would this increase performance? How could I "force" my program to use stack instead of heap?What other or better options do I have for
DDto be defined? I replacedEigen::Vectorbystd::vectorwhich didn't really change anything, at least on performance side.
I need to read from DD all the time, so any help is highly appreciated.
std::vector<int>does not live on the stack even though anintdoes. And that having both the vector and the matrix dynamic adds overheads also makes sense as it means that the matrices don't lie on the heap in an orderly, consecutive fashion (in addition to allocation overheads). As this does not seem like a vector in the linear algebra sense (needing certain member functions / interfaces), I would go with thestd::vector.Eigen::VectorX<Eigen::Matrix<double, 9, 10>>vsstd::vector<Eigen::Matrix<double, 9, 10>>is saving 8 bytes of stack memory. The actual data is stored on the heap in both cases. If you have a possibly dynamically growing or a large array of data of the same type (almost) always usestd::vector(unless you have a good reason not to).