-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?

4
  • 16
    The compiler probably produces the same assembly code. It is better to resolve these issues empirically than to theorise. Commented Jun 14, 2013 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. Commented Jun 14, 2013 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 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. Commented Jun 15, 2013 at 18:09
  • See also: Is Fortran faster than C. Commented Jun 15, 2013 at 18:12

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.