1

Should primitive array content be accessed by int for best performance? Here's an example

int[] arr = new arr[]{1,2,3,4,5};

Array is only 5 elements in length, so the index doesn't have to be int, but short or byte, that would save useless 3 byte memory allocation if byte is used instead of int. Of course, if only i know that array wont overflow size of 255.

byte index = 1;
int value = arr[index];

But does this work as good as it sounds?

Im worried about how this is executed on lower level, does index gets casted to int or other operations which would actually slow down the whole process instead of this optimizing it.

Scavs
  • 673
  • 1
  • 5
  • 16

2 Answers2

2

In C and C++, arr[index] is formally equivalent to *(arr + index). Your concerns about casting should be answerable in terms of the simpler question about what the machine will do when it needs to add add an integer offset to a pointer.

I think it's safe to say that on most modern machines when you add a "byte" to a pointer, its going to use the same instruction as it would if you added a 32-bit integer to a pointer. And indeed it's still going to represent that byte using the machine word size, padded with some unused space. So this isn't going to make using the array faster.

Your optimization might make a difference if you need to store millions of these indices in a table, and then using byte instead of int would use 4 times less memory and take less time to move that memory around. If the array you are indexing is huge, and the index needs to be larger than the machine word side, then that's a different consideration. But I think it's safe to say that in most normal situations this optimization doesn't really make sense, and size_t is probably the most appropriate generic type for array indices all things being equal (since it corresponds exactly to the machine word size, on the majority of architectures).

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
1

does index gets casted to int or other operations which would actually slow down the whole process instead of this optimizing it

No, but

that would save useless 3 byte memory allocation

You don't gain anything by saving 3 bytes.

Only if you are storing a huge array of those indices then the amount of space you would save might make it a worthwhile investment.

Otherwise stick with a plain int, it's the processor's native word size and thus the fastest.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • "You don't gain anything by saving 3 bytes." How is that you don't? You do save by not storing useless 3 bytes in L1 cache and it would make difference under extremely large object count processing. – Scavs Aug 15 '15 at 15:46
  • @UmNyobe one per object, but object count is extremely large. The question is more not about project this solution will be used or premature optimizations. Id just like to know about this regardless of current usage. – Scavs Aug 15 '15 at 19:34