p is an array and N is a large number. Which of the following two
loops is faster?
Neither.
It seems that Case 1 needs multiplication/shifting to calculate the
address/index and the second case needs only an ADD operation. But I
tested it, the speed is almost the same. Can anybody tell me why?
Because you don't understand C.
There is no requirement that the actual operations performed be the ones
you think you have described; all that's required is that the output is
the same.
Compilers typically know most of the common loop idioms and express them
well.
Let me put it more directly: If you are wasting your time thinking about
whether or not one of these loops is "faster", you are unlikely to ever
become a good programmer. Turn back from that path of madness.
Write code that is clear, effective, and easy to understand. If you find
that it is not fast enough, start by profiling it to see where the time
is going. Look at the things that are taking the most time. See if there is
a way to change your algorithm to reduce their frequency; if you are
calling a comparison routine millions of times, a switch of sorting
algorithms can reduce that to tens of thousands, or a week's back-breaking
effort can reduce the cost of each call by 10%.
Don't try to figure out "what really happens", because that's not how C
works. What really happens is the compiler does something magical that
happens to result in the results that would have happened according to the
behavior of the abstract machine. Don't waste your time trying to guess
whether or not there are multiplies or something like that involved;
stick to the abstractions, and you'll have a better feel for what to expect.
-s