C / C ++: which is faster: for loop or pointer increment

I am wondering which of the following code segments will be the fastest, assuming that the goal is to read from the elements of the type Tin the quantity numElementspointed somePointerto and do something with them. I am particularly interested in the efficiency of the cycle structure itself, and not what is done with the elements.

1st candidate

for (int i = 0; i < numElements; i++) {
    T val = somePointer[i];
    ... // Do something
}

2nd candidate

T* tempPointer = somePointer;
T* endPointer = somePointer + numElements;
while (tempPointer < endPointer) {
    T val = *tempPointer;
    ... // Do something
    tempPointer++;
}

, . , , , , , , . for i , , somePointer, i * sizeOf(t) . , -, , , .

, , for SIMD; for, , for . , , , , for , .

, , ?

+4
3

, - , .

     , ,      ( ,       ).

C, , , . , , int (, , size_t).

, , .. , , , ( , ) . - , , , ... (, , , ..).

" ?" , , gcc . -. , (-O3, ).

, . , , . , .

, : -, , , , . , ! , , , ...

. ( , - ) , , , , , ... .

, , , . , , .

. ...

+4

, for, while, , - O (n). , , .

, , , , ,

//Do something

- .

, , .

, for/while , .

, !

+1

, GCC MinGW Cygwin Intel. Intel , , , , , , , , , , / . ( . )

gcc -S one.c
gcc -S two.c

to see the assembly code. If you understand the x86 build, you can probably more clearly understand what I want to say. My understanding is that the first cycle will work faster if you go deep into how processors and assembly work.

-1
source

All Articles