memcpy内存拷贝的改进与优化
3,836 views
0
原版:
void *memcpy( void *dest, const void *src, size_t count ) { ASSERT((dest != NULL)&&(src != NULL)); char *temp_dest = (char *)dest; char *temp_src = (char *)src; while(count--) // 不对是否存在重叠区域进行判断 { *temp_dest++ = *temp_src++; } return dest; }
改进一:
void* memcpy(void* dest, void* source, size_t count) { void* ret = dest; if (dest <= source || dest >= (source + count)) { //Non-Overlapping Buffers //copy from lower addresses to higher addresses while (count --) *dest++ = *source++; } else { //Overlapping Buffers //copy from higher addresses to lower addresses dest += count - 1; source += count - 1; while (count--) *dest-- = *source--;l } return ret; }
改进二:
void memcpy(void* dest, const void* src, size_t n) { assert((((uintptr_t) dest | (uintptr_t) src | n) & 0x03) == 0); uint32_t* d = (uint32_t*) dest; const uint32_t* s = (uint32_t*) src; n /= sizeof(uint32_t); if (d < s) { /* copy forward */ while (n--) { *d++ = *s++; } } else { /* copy backward */ d += n; s += n; while (n--) { *--d = *--s; } } }
原文: memcpy内存拷贝的改进与优化
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2012-01-01 23:17:45
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: memcpy内存拷贝的改进与优化 (米扑博客)