Re: array index and pointer, which is faster?
- From: richard@xxxxxxxxxxxxxxx (Richard Tobin)
- Date: 29 Feb 2008 17:03:07 GMT
In article <a0f7f683-76a1-4222-b1a4-ff58de391d66@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
Xiaohan <wangxiaohan@xxxxxxxxx> wrote:
p is an array and N is a large number. Which of the following two
loops is faster?
Case1:
for(i=0; i<N; i++){
p[i] = i;
}
Case2:
for(i=0; i<N; i++){
*p = i;
p++;
}
Depends entirely on your compiler. With a good compiler it shouldn't
make any difference: optimising indexing in a loop to pointer arithmetic
was common in the 1970s if not before.
Other things being equal I would prefer the array indexing version,
since in more complicated cases it might let the compiler see that
there is no aliasing.
It seems that Case 1 needs multiplication/shifting to calculate the
address/index and the second case needs only an ADD operation.
That's only true if your compiler doesn't optimise one to the other.
But in any case, a shift operation on a register is extremely quick.
And for large amounts of data, the limiting factor will be memory
access so that it won't make any difference at all.
-- Richard
--
:wq
.
- References:
- array index and pointer, which is faster?
- From: Xiaohan
- array index and pointer, which is faster?
- Prev by Date: Re: dual core and c
- Next by Date: Re: Is there stack associated when a executing an inline function?
- Previous by thread: array index and pointer, which is faster?
- Next by thread: Re: array index and pointer, which is faster?
- Index(es):
Relevant Pages
|