Question

Which implementation is better and why?

Element by Element comparison using a for loop or memcmp() implementation

int a[] = {1,2,3};
int b[] = {1,3,5};

memcmp(a, b, sizeof(int)*n)

OR

 for (i = 0; i < n ; i++)
    {
       if (a[i] == b[i])
        {
            /* some Code */
        }
    }
Était-ce utile?

La solution

memcmp is faster: it is generally heavily optimized by the compiler to use special instructions on the cpu, loop unrolling, and other "advanced" techniques that the generated code for the simple loop (generally) won't use. However, memcmp can only compare byte values; it is fine in case of an array of integers, but it (probably) wouldn't work for an array of objects.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top