Array indexing vs. pointers...

Richard Harter g-rh at xait.CCA.COM
Tue Sep 20 05:57:16 AEST 1988


In article <8809191521.AA17824 at ucbvax.Berkeley.EDU> U23405 at UICVM (Michael J. Steiner) writes:
>First, I have a question. How and why is array indexing slower than
>pointer arithmetic? They are very similar. Also, I think that compilers
>should automatically translate array indexing into pointer arithmetic when
>dealing with arrays in C. Any comments, opinions?

	Depends on the compiler, the machine, and the circumstances.  The
gain comes when you increment a pointer into the array rather than reference
the indexed array.  For example

	for (i=0;i<n;i++) {
	  a batch of code referring to a[i]
	  }
versus
	tmp = a;
	for (i=0;i<n;,i++,tmp++) {
	  same code referring to *tmp
	  }

In the first instance a[i] is equivalent to *(a+i) and most compilers will
treat them much the same.  The add has to be done each time a[i] is referred
to.  In the second case there is no add but there is an increment once through.
A smart compiler will take the first instance and generate something like

	tmp = a;
	for (i=0;i<n;i++) {
	  tmp1 = *tmp++;
	  same code referring to tmp1
	  }

If execution efficiency is your concern and your environment includes simple
compilers there is profit to be got by doing your own optimization as above.
The down side is that your hand optimization may interfere with the clever
tricks of an optimizing compiler and you lose ground by doing hand
optimization.  There ain't no justice.
-- 

In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
	Richard Harter, SMDS  Inc.



More information about the Comp.lang.c mailing list