Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!purdue!ames!oliveb!sun!david@sun.com From: david@sun.com (The Amazing Elvis Hypnodisk) Newsgroups: comp.lang.c Subject: Re: Another s*y question (cost of scaling and code diddling) Message-ID: <102564@sun.Eng.Sun.COM> Date: 3 May 89 07:11:33 GMT References: <2459@nmtsun.nmt.edu> <10135@smoke.BRL.MIL> <1266@l.cc.purdue.edu> <629@gonzo.UUCP> Sender: david@sun.Eng.Sun.COM Lines: 49 In article <629@gonzo.UUCP> daveb@gonzo.UUCP (Dave Brower) writes: >Looking into this, I discovered at least one counter-intuitive result, >Many people have jumped on this, but it does point to one of the >fundamental C mind sets, which turns out to have some exceptions: > > "For heavy array operations, it is usually faster to > use pointers than array indexing." > - me. > >That is because the scaling operation is only done once, when the >pointer is incremented, rather than at each reference to the >array[index]. Specifically, where a and b are arrays of non-char types: > > for( ap = a, bp = b; i--; ) /* even I will use a comma op here! */ > *ap++ = *bp++; > >Is likely to be noticably faster than the functionally equivalent: > > while( i-- ) > a[i] = b[i]; Another counter-intuitive result is the Sun-4. The current Sun SPARC C compiler will usually generate better code for arrays than for pointers. This is mostly because of the SPARC instruction set (it has reg + reg addressing but no autoincrement or memory to memory ops). The best pointer code would be something like (neglecting loop unrolling): 1: ld [%ap], %tmp inc size, %ap st %tmp, [%bp] deccc %i bnz 1b inc size, %bp ! delay slot while the best array code might be: 1: ld [%aend + %off], %tmp inccc size, %off bnz 1b st %tmp, [%bend + %off] ! delay slot where aend = a + i, bend = b + i - 1, off = -i * sizeof *a, and of course sizeof *a == sizeof *b. Not that a compiler couldn't tranform one into the other. Not that I'm in the Sun compiler group. Remember, cc -S is your friend. -- David DiGiacomo, Sun Microsystems, Mt. View, CA sun!david david@sun.com