0

I was wondering which is the fastest for general use. So instead of push_back() we could use the following code for arrays. I thought arrays are faster but I am not sure of that.

 int *p;
 p = new int[5];
 for(int i=0;i<5;i++)
    *(p+i)=i;

 // realloc
 int* temp = new int[6];
 std::copy(p, p + 5, temp); 
 delete [] p;
 p = temp; 
gelatine1
  • 199
  • 1
  • 3
  • 11
  • 4
    Put the profiler on it. :) – Almo Feb 06 '14 at 19:15
  • Just use std::vector - Already implemented – Ed Heal Feb 06 '14 at 19:16
  • 2
    In general, a "real" C array will be faster to access than any sort of object. (But of course rapid access is not the only criterion for choosing a construct.) – Hot Licks Feb 06 '14 at 19:16
  • 2
    This is exactly what `std::vector` is doing under the hood, only with automatic memory management, exception safety, amortized re-size cost, etc. etc. – Oliver Charlesworth Feb 06 '14 at 19:16
  • 1
    an array will usually be "faster" than a vector, but like the previous comments said, `std::vector` handles everything for you.. the impact to speed should be negligible, not worth worrying about :) – dub stylee Feb 06 '14 at 19:17

1 Answers1

4

Implementations of std::vector are usually optimized for general use. For any specific case, a native array will be better or equal performance, but if you don't know the exact usage characteristics up front, a vector will usually be decent performance, and better than a native array that hasn't been thought through. For example, in the code above, you explicitly reallocate the memory, while a vector implementation might have already allocated enough memory (e.g. to make the vector a minimum of one cache line).

MooseBoys
  • 6,641
  • 1
  • 19
  • 43
  • let's not forget that with a good `allocator` an `std::vector` might get really interesting performances with almost 0 effort, especially pool allocators. – user2485710 Feb 06 '14 at 19:38