1

I'm working on a synth and I have some code that's going slower than I'd like. I've narrowed down the culprit to some nested for loops which iterate over a 3 dimensional vector of floats. Given that this part of my code is the current bottle neck, I'd like to optimize it as best as I can.

My current understanding of 2d C arrays is that they are really just one long linearly-nested array with some fancy syntax.

int* myArray[3][3];
pseudoSetEntriesToRowNum(myArray);
for (int i = 0; i < 9; i++) {
  cout << myArray[i];
}
// output: 000111222

As for vectors, (when 1D) the performance seems to be widely sufficient (Using arrays or std::vectors in C++, what's the performance gap?) with issues arising more from resizing than accessing/setting. But when 2d, my understanding would suggest that the linearly-nested optimization is lost, and that for each dimension a pointer is being followed.

vector<vector<int>> myVector = pseudoMake2dVectorWithRowNumAsEntries(3, 3);
int* myArray = &(myVector[0][0]);
for (int i = 0; i < 9; i++) {
  cout << myArray[i];  // this should not be okay
}
// (my guess of) output: 0,0,0, BAD_ACCESS * 6

My question on this topic is first, am I even thinking about this correctly? And, if I am, would the implication be that 2D+ dimensional vectors are not good for time sensitive operations? And if 2D+ dimensional vectors are not ideal, what are some good alternatives?

Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • 1
    It depends on how you put together the 2D array. [See this as an example](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048). – PaulMcKenzie Mar 03 '19 at 21:38
  • 1
    @πάντα ῥεῖ please read the questions before marking them as duplicates. I linked the "duplicate" in my question, and this is an entirely different one having to do with multi-dimensional arrays. – Seph Reed Mar 03 '19 at 21:40
  • 1
    Your guess is correct. The three inner vectors do not necessarily occupy consecutive areas of memory because the outer array is just 3 pointers..You can always serialize 2D+ arrays into 1D by defining order of traversal. E.g. `[i][j]`->`[i*+j]`. – Quimby Mar 03 '19 at 21:41
  • @SephReed Number of dimensions isn't relevant, the answers from the marked duplicate still apply. – πάντα ῥεῖ Mar 03 '19 at 21:43
  • 1
    @πάνταῥεῖ I'm getting mixed information. Quimby says multi-dimensional vectors do not necessarily serialize. Would you mind linking to the specific part of your linked question which covers this subject? – Seph Reed Mar 03 '19 at 21:48
  • 1
    @SephReed Multi dimensional nested `std::vector` won't guarantee contiguous memory blocks, and thus are CPU cache unfriendly for some certain operations. Hence the discussion about performance hits. – πάντα ῥεῖ Mar 03 '19 at 21:51
  • 1
    https://stackoverflow.com/a/54974157/4808079 Better than nothing. – Seph Reed Mar 03 '19 at 21:59

0 Answers0