Reputation: 45
I just need to know which array is faster : a 2D char array or a 1D array to char pointers.
for example :
char* name1[]={"Marc", "Jean-Marie", "Paul", ...}
char name2[][11]={"Marc", "Jean-Marie", "Paul", ...}
if I have the same exact code that would sort these arrays which one would finish faster ?
Upvotes: 2
Views: 84
Reputation: 63471
Sorting the second variant will require string copies using an intermediate buffer or byte-for-byte / block-based swapping. It's likely that this will be "slower" than simply moving pointers.
Conversely, using pointers to actual string literals means only swapping pointers as you sort. So it's likely that this will be "faster".
Furthermore, it's likely that your string literals will be packed closer together in memory by the compiler, which can help cache performance, assuming you actually want to sort a much larger number of strings than 3.
For the example you give, however. It's not completely clear-cut. On a system with larger native types (e.g. pointers, or special SIMD enhancements) it's entirely possible that swapping around strings in the 2D array can be optimized to the point where you can barely measure a difference. Although this is highly dependent on the underlying memory architecture, and whether it cares much about alignment.
A final point is that if you have a very large 2D array, it would need to be allocated either statically or on the heap, as it may not fit on the stack.
And of course, you may only begin to see measurable differences at very large array sizes. Using an example with 3 strings is pretty ridiculous.
Upvotes: 3
Reputation: 8614
Firstly, for such a small number of elements it really does not matter. Both are equally fast.
However when you have a large number of elements in the array, you need to look at cache access.
For name1
you have an array or pointers. The pointers itself point to some other location where the string literals "Marc"
Jean-Marie"
etc are stored. This may cause issues with caching the arrays properly.
For name2
the strings "Marc"
etc are copied into the array. This may be easier for cache. However, you should note that if you have a large array the second approach will cause more use of RAM.
Upvotes: 0