我发现bionic中的memcmp.c是这样的:
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 }在for循环中,相同的逻辑重复了4次,为什么?能不能不重复?
谢谢,维克多
发布于 2012-06-20 13:37:48
这是一个手动循环展开。它可以只做一次,甚至用一个规则的循环来代替无限的循环,它也可以做超过4次。有人认为这给了编译器更好的机会来优化生成的代码。
有关更多信息,请查看http://en.wikipedia.org/wiki/Loop_unrolling
https://stackoverflow.com/questions/11113404
复制相似问题