Array indexing vs. pointers...

Robert W Berry rwberry at hubcap.UUCP
Tue Sep 20 04:33:46 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?
> 
>                                                  Michael Steiner
>                                                  Email: U23405 at UICVM.BITNET
	Indexing requires that a constant (also called an offset) be added
to the beginning of the array for each and every reference.  This overhead
is the number one reason that array indexing is slower than pointer
manipulation.  (Today's C compilers often view the beginning of the array
as a constant and add the offset from a register which is ideal for 
sequential memory accesses.)
	Pointers, on the other hand, make use of today's larger word sizes
to directly address the object in question.  More efficient, and much 
faster.
	With today's optimizing compilers this is often a moot point.
Many compilers end up implementing both array indexing and pointer
manipulation using indirect addressing (adding the value stored in one
register to the value stored in another register to calculate and effective
address.)  Especially in a segmented memory architecture.  The end result
is that both techniques end up running in about the same time.  
	Be wary however, because there are also a lot of compilers on the
market that use different techniques for array indexing and pointer
manipulation.  So when in doubt, use pointers.  They're _almost_ always
faster (and closer to the way God intended people to program ;-)!)
	One good way to get a feel for this type of situation is to have
your C compiler compile some source stubs into assembler (OH NO, ANYTHING
BUT ASSEMBLER) and watch the way things REALLY happen with your C compiler.
Even if you're not an assembler expert, some things become pretty obvious
when you see them on a machine level.
	Happy Programming,
	Bob



More information about the Comp.lang.c mailing list