2010-05-24 65 views
1

在Obj-C程序中使用memset或memcpy时,编译器是否将数据的设置(memset)或复制(memcpy)优化为32位写入,还是逐字节地执行?使用memcpy/memset

+1

我怀疑是否有任何现代实现可以逐字节地执行此操作,除了特殊情况,例如对齐问题等。 – Ofir 2010-05-24 08:22:12

回答

0

Memset将作为标准C库的一部分,因此它取决于您正在使用的实现。我猜想大多数实现将复制本地CPU大小(32/64位)的块,然后逐个字节地复制余数。

这里的glibc的版本的memcpy的示例实现:

void * 
memcpy (dstpp, srcpp, len) 
    void *dstpp; 
    const void *srcpp; 
    size_t len; 
{ 
    unsigned long int dstp = (long int) dstpp; 
    unsigned long int srcp = (long int) srcpp; 

    /* Copy from the beginning to the end. */ 

    /* If there not too few bytes to copy, use word copy. */ 
    if (len >= OP_T_THRES) 
    { 
     /* Copy just a few bytes to make DSTP aligned. */ 
     len -= (-dstp) % OPSIZ; 
     BYTE_COPY_FWD (dstp, srcp, (-dstp) % OPSIZ); 

     /* Copy whole pages from SRCP to DSTP by virtual address manipulation, 
    as much as possible. */ 

     PAGE_COPY_FWD_MAYBE (dstp, srcp, len, len); 

     /* Copy from SRCP to DSTP taking advantage of the known alignment of 
    DSTP. Number of bytes remaining is put in the third argument, 
    i.e. in LEN. This number may vary from machine to machine. */ 

     WORD_COPY_FWD (dstp, srcp, len, len); 

     /* Fall out and copy the tail. */ 
    } 

    /* There are just a few bytes to copy. Use byte memory operations. */ 
    BYTE_COPY_FWD (dstp, srcp, len); 

    return dstpp; 
} 

所以,你可以看到它再次复制几个字节抢先对齐,然后拷贝的话,那么最后以字节为单位。它使用某些内核操作进行了一些优化的页面复制。

2

您可以在Darwin source中看到这些方法的libc实现。在10.6.3中,memset在单词级别工作。我没有检查memcpy,但可能它是一样的。

你是对的,编译器可以做内联工作而不是调用这些函数。我想我会让一个懂得更好的人回答它会做什么,但我不会指望有问题。