memcpy函数实现中的优化

今天浏览Google面试题的时候,有看到一个memcpy的实现,以及如何去优化memcpy。

我对memcpy的实现的记忆就是,拷贝的时候需要从后往前拷贝,为何防止内存重叠。 但是如果去优化它我没有想过。

 

原来,这里提到的一个优化方法也挺朴素的,智商捉鸡。这里的话可以一个字长一个字长的拷贝,而不需要逐个字节来拷贝。

可以参考下面的实现。

复制代码
 1 void *mymemcpy(void *dst,const void *src,size_t num)
 2 {
 3     assert((dst!=NULL)&&(src!=NULL));
 4     int wordnum = num/4;//计算有多少个32位,按4字节拷贝
 5     int slice = num%4;//剩余的按字节拷贝
 6     int * pintsrc = (int *)src;
 7     int * pintdst = (int *)dst;
 8     while(wordnum--)*pintdst++ = *pintsrc++;
 9     while (slice--)*((char *)pintdst++) =*((char *)pintsrc++);
10     return dst;
11 }
复制代码

 

posted on   Stomach_ache  阅读(625)  评论(0编辑  收藏  举报

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示