Search code examples
cperformancepointers

Index vs. Pointer


I'm using arrays of elements, many of which referencing each other, and I assumed in that case it's more efficient to use pointers. But in some cases I need to know the index of an element I have the pointer to. For example I have p = &a[i] and I need to know the value of i. As I understand it, i can be computed through p - a. But this operation inherently involves division, which is expensive, whereas computing an address from an array index involves a multiplication and is faster.

So my question is, is cross referencing with pointers in a case where you need the indexes as well even worth it?


Solution

  • But this operation inherently involves division, which is expensive, whereas computing an address from an array index involves a multiplication and is faster.

    This operation requires a division only when the size of the element is not a power of two, i.e. when it is not a pointer, or some standard type on most systems. Dividing by a power of two is done using bit shifting, which is extremely cheap.

    computing an address from an array index involves a multiplication and is faster.

    Same logic applies here, except the compiler shifts left instead of shifting right.

    is cross referencing with pointers in a case where you need the indexes as well even worth it?

    Counting CPU cycles without profiling is a case of premature optimization - a bad thing to consider when you are starting your design.

    A more important consideration is that indexes are more robust, because they often survive array reallocation.

    Consider an example: let's say you have an array that grows dynamically as you add elements to its back, an index into that array, and a pointer into that array. You add an element to the array, exhausting its capacity, so now it must grow. You call realloc, and get a new array (or an old array if there was enough extra memory after the "official" end). The pointer that you held is now invalid; the index, however, is still valid.