Array indexing vs. pointers...
Steve Summit
scs at athena.mit.edu
Tue Sep 20 15:47:58 AEST 1988
WARNING: Heretical C advice follows. Efficiency hackers please
read no further.
In article <8809191521.AA17824 at ucbvax.Berkeley.EDU> Michael J. Steiner writes:
>How and why is array indexing slower than pointer arithmetic?
>I think that compilers should automatically translate array indexing
>into pointer arithmetic when dealing with arrays in C.
Array indexing may be slower, but it may also be easier (for
human readers of the program) to understand. If there is the
slightest chance that using array indexing instead of pointers
will make your code clearer, I'd like to encourage you to stick
with the indices, unless your program ends up running too slowly,
and profiling shows the array indices to be at fault. Chances
are it won't run noticeably slower, in part because there are
good compilers which, in the spirit of your suggestion,
effectively use a pointer reference in the generated code.
This is not to say that array indexing is always clearer than
pointers--often, a well-conceived pointer algorithm is the right
one to use for both clarity and efficiency. It's a judgement
call. But some code is just ridiculously clearer to the
uninitiated if it uses indices rather than pointers, and at no
cost in overall efficiency. A perfect example is argv parsing;
compare
while(--argc)
if(**++argv == '-')
processoption(*argv);
else processfile(*argv);
with
for(i = 1; i < argc; i++)
if(argv[i][0] == '-')
processoption(argv[i]);
else processfile(argv[i]);
The second example may use an extra variable, but it's a lot more
obvious that argv[0] is skipped (as it should be) and it has the
additional benefit of leaving the initial values of argc and argv
undisturbed.
Steve Summit
scs at adam.pika.mit.edu
More information about the Comp.lang.c
mailing list