memcpy函數實現中的優化

今天瀏覽Google面試題的時候,有看到一個memcpy的實現,以及如何去優化memcpy。c++

我對memcpy的實現的記憶就是,拷貝的時候須要從後往前拷貝,爲什麼防止內存重疊。 可是若是去優化它我沒有想過。面試

 

原來,這裏提到的一個優化方法也挺樸素的,智商捉雞。這裏的話能夠一個字長一個字長的拷貝,而不須要逐個字節來拷貝。優化

能夠參考下面的實現。spa

 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 }
相關文章
相關標籤/搜索