I found memcmp.c in bionic is like this:

 30 int memcmp(const void *s1, const void *s2, size_t n)
 31 {
 32     const unsigned char*  p1   = s1;
 33     const unsigned char*  end1 = p1 + n;
 34     const unsigned char*  p2   = s2;
 35     int                   d = 0;
 36 
 37     for (;;) {
 38         if (d || p1 >= end1) break;
 39         d = (int)*p1++ - (int)*p2++;
 40 
 41         if (d || p1 >= end1) break;
 42         d = (int)*p1++ - (int)*p2++;
 43 
 44         if (d || p1 >= end1) break;
 45         d = (int)*p1++ - (int)*p2++;
 46 
 47         if (d || p1 >= end1) break;
 48         d = (int)*p1++ - (int)*p2++;
 49     }
 50     return d;
 51 }

In the for loop, the same logic repeats 4 times, why? Can it no repeat?

Thx, Victor

有帮助吗?

解决方案

That's a manual loop unrolling. It could be done just once, or even with a regular loop instead of the infinite one, it could also be done more than 4 times. Someone considered this gives the compiler a better chance to optimize the generated code.

For more information, check http://en.wikipedia.org/wiki/Loop_unrolling

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top