Re: array index and pointer, which is faster?



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
.



Relevant Pages

  • Re: Rules for "colon matching" in array operations
    ... < "scalarization pass inside of the compiler". ... Similarly, Andy talks about loops, but not ... Any routine using ENTRY compiles as one function ...
    (comp.lang.fortran)
  • Re: Support for optimization for dual core proc in C++
    ... Does the C++ in VS2005 allow optimization to parallelize and vectorize ... automatically like the product IntelC++ Compiler Version 10.0 does? ... restructures and optimizes loops to ensure that auto-vectorization, ...
    (microsoft.public.vc.language)
  • Re: Why is C# 450% slower than C++ on nested loops ??
    ... A nested loop written the way it is in the benchmark is measuring nothing but a compiler's ability to optimize nested loops that do more or less nothing. ... C# compiler generates such code, and the C++/CLI compiler is able to do so. ... It is reported that 2005 does a much better job of optimization of .NET code, yet, only with the C++, not the C# compiler. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: File IO
    ... > (Actually, from your description, the implicit DO loops are working ... your problem is when you read array slices instead of implicit DO ... so the compiler might creat a temporary ... that's probably a bug in the I/O design. ...
    (comp.lang.fortran)
  • Re: Support for optimization for dual core proc in C++
    ... Having a syntax in for loops to have them done in parallel without ... OLE Type Libraries are language and compiler independent. ... the Intel compiler should have no problem with those. ... Does the C++ in VS2005 allow optimization to parallelize and vectorize ...
    (microsoft.public.vc.language)