Is it true that using pointers is significantly faster than using array syntax in C?

With current C compilers, is it true that using array syntax (a [i]) is slower than using pointers (* (p + i))?

+3
source share
10 answers

They must be the same. But:

for( i = 0; i < ...; ++ i ) ... array[i] ...

may be slower than:

for( p = array; *p; ++ p ) ... *p ...

because in the first case, the compiler may be needed *(array+i), and in the second you are simple (*p).

In trivial cases, however, the compiler must be able to optimize and generate the same machine code.

+9
source

. - .

+11

, C ++ a[i] *(a+i). , a[1] 1[a]. :)

+8

x86 x86_64 p[i] *(p+i) ( : C) , p , , i - . x86 /, , 2.

, i p, , , . x86:

  • a (static extern global) , PIC, a[i] *p ( i) (, 0xdeadbeef(,%ecx,4) vs (%esi)).
  • a ( ), , a[i] *p (, 12(%esp,%ecx,4) vs (%esi) %esp, ).
  • a PIC, a[i], , , *p, i .
  • a , , a[i] , *p (, (%eax,%ecx,4) vs (%esi)).
+3

, -

while (*s++ = *d++)
   ;

,

while (s[i] = d[i])
   i++;

, , .

+2

, .

.

+1

. , ,

int a[];
for (int n = 0; n < size; n++) { ... Do stuff with a[n]; }

a,

int a[size];
int *end = a + size;
for (int *i = a; i != end; ++i) { ... Do the same stuff with *i ; }

, .

+1

, , , .

// which is faster? *t or t[i]?
process_some_array(T *t, size_t n)
{
    T *end = &t[n];
    for (T *t = t; t < end; ++t)
        // do stuff with *t
    for (size_t i = 0; i < n; ++i)
        // do stuff with t[i]
}

, . , , . , , .

, , , , . .

+1

. , . . - .

0

Source: https://habr.com/ru/post/1774790/


All Articles