-2

Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name?

How does the compiler treat both approaches?

Zzz
  • 2,927
  • 5
  • 36
  • 58
  • 16
    The compiler probably produces the same assembly code. It is better to resolve these issues empirically than to theorise. – juanchopanza Jun 14 '13 at 18:41
  • 2
    Write code that's readable. If there really is a performance bottleneck from using one version over another **and** you've run a profiler to confirm that this is indeed the root cause, then you can start to make these sorts of microoptimizations. Doing this early in a program just makes it harder to read and risks introducing bugs. – templatetypedef Jun 14 '13 at 18:46
  • Your question was closed. I would vote to re-open if you were to show some use case. Why would the language designers give two choices? Obviously, pointers are better in some cases and array indexes in others. Google: *pointer aliasing*, and see [mem-ssa](http://www.airs.com/dnovillo/Papers/mem-ssa.pdf) paper for why an *array* **MAY** be faster. Others gave reasons why a pointer maybe faster. Fortran is often shown to give better *matrix* performance just because programmers **can not** use pointers. It depends on the *algorithm*, the *programmer* and the *compiler*. – artless noise Jun 15 '13 at 18:09
  • See also: [Is Fortran faster than C](http://stackoverflow.com/questions/146159/is-fortran-faster-than-c). – artless noise Jun 15 '13 at 18:12

2 Answers2

4

Any modern compiler should produce an equivalent assembly code for both methods.

Andrej Palicka
  • 971
  • 1
  • 11
  • 26
1

I did a short test. I created int arr[10] and set all cells to 10 using normal for loop indexed by int and one using int*.

What was strange form me (I accept Midhun MP arguments) pointer indexed loop assembly code was larger then normal approach (1 line more). But when I turn O3 optimization output was exactly the same.

IMO code should be easy to read and work without errors on the first place. Micro optimization can be done only if you really need them. In other cases readability beats performance.

If you are curious how it works. Just do this test yourself. Prepare 2 versions of code, compile it with gcc -S and diff outputs.

janisz
  • 6,292
  • 4
  • 37
  • 70