-1

I'm coding what has to be a high-performance program.

What I have now is an array of vectors of type "A" that I've invented. The "A" is an struct that have a long long and a double.

vector<A>* ord = new vector<A>[X];

Where X is a value that i don't know until executing time.

What I have to do is, for each vector, sort its objects by the long long variable and then perform some operations.

My question is, it's better in terms of performance what I have now `An array of vectors' or it's better to create a vector of vectors like this:

vector<vector<A>> ord;

Two thinks:

  • Notice that I don't have to do operations between vectors.
  • I have read in other post that it's a bad idea to use `new' operator, in this case, what I shoud use in my program.
david.t_92
  • 1,341
  • 8
  • 13
  • https://ericlippert.com/2012/12/17/performance-rant/ Though honestly I don't see how the first version would be faster (as long as you use the `std::vector` properly) – UnholySheep Jan 13 '18 at 19:49
  • 2
    Unless you have determined that there is a real performance bottleneck due to having `std::vector>` then don't complicate things with the alternative. Even if you did find a bottleneck, I doubt that using a C array instead would help at all. Finally, if you need an owning pointer, prefer `std::unique_ptr` over raw owning pointers. – François Andrieux Jan 13 '18 at 19:49
  • The algorithms you choose to sort and perform your *"other operations"*, and whether you are able to use SIMD or other optimisations, and whether you multi-thread your code are probably more likely to have a far greater impact than whether you use `new` or a vector, IMHO. – Mark Setchell Jan 13 '18 at 20:18

2 Answers2

2

A dynamically allocated array of vectors and a vector of vectors will likely be the same in optimized code. And the vector of vectors takes care of so many problems that unless you have some very unusual problem you should prefer that solution as a matter of course.

Premature optimization is the root of all evil - Sir Tony Hoare

SoronelHaetir
  • 11,346
  • 1
  • 8
  • 18
0

You mention "X is a value that i don't know until executing time", does that mean its static?

If you need it to be dynamic use vectors, but if X doesn't change use arrays as it will save you a bit of memory (both will run at pretty much the same speed if X is static).

As for your question on when to use new, I'll defer to this post: When to use "new" and when not to, in C++?

Vice
  • 242
  • 2
  • 5