Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros & cons of using an array of structures versus an array of pointers to a structure?

I'm trying to decide which I should use.

The pros of pointers to structures that I can think off the top of my head.

  • Less space wasted if you don't use all elements of your array.
  • Less overheard when swapping array elements

Any other pro's/con's for both sides?

like image 219
Michael Avatar asked Dec 04 '22 18:12

Michael


2 Answers

There's a few other differences in these approaches:

  • The array-of-pointers approach reduces the overhead in resizing the array;
  • The array-of-pointers approach gives you an "empty" / "unused" value (NULL). If this is semantically valid in your application, then this is an advantage (you don't have to alter your struct itself to express this);
  • The array-of-pointers approach allows multiple elements of the array to refer to the same struct rather than a copy. Again, this is only an advantage if this situation is semantically reasonable for your application;
  • The array-of-structures approach provides more locality of reference (structs close together in the array are also close together in memory, which can be a performance advantage in some situations);
  • For very large numbers of items, the array-of-structures approach requires a large contiguous block of memory, which may not be available if your process address space has become fragmented.
like image 82
caf Avatar answered Dec 07 '22 23:12

caf


An downside of using array of pointers, or pointers in general is:

Pointers would (most likely)involve using dynamic memory allocations and that implies manual management of this dynamic memory.
Dynamic memory allocations are little slower than stack allocations.
Also, using dynamic memory is more usage error prone.

Having said that, which one to choose actually depends on:

  • How bulky your structures are
  • Are number of structures required known at compile time
  • How often do you need to swap structures
like image 45
Alok Save Avatar answered Dec 07 '22 22:12

Alok Save