memcpy() 通常比 strcpy() 快吗? [英] Is memcpy() usually faster than strcpy()?

查看:117
本文介绍了memcpy() 通常比 strcpy() 快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

memcpy() 通常比 strcpy() 快吗(在大多数真实平台上)?(我假设字符串的大小是已知的.)

Is memcpy() usually faster than strcpy() (on most real platforms)? (I assume that size of the string is known.)

如果我没记错 i386 汇编程序,有 loop 指令可以复制给定数量的字节或字.所以这是最快的方法,而 strcpy() i386 汇编器实现将在普通循环中手动检查 '\0'.

If I remember i386 assembler correctly, there are loop instructions which copy a given number of bytes or words. So it is the fastest way, while strcpy() i386 assembler implementation would use manual checking for '\0' in a plain loop.

所以我觉得在 x86 上 memcpy()strcpy() 快.

So I feel that on x86 memcpy() is faster than strcpy().

其他架构怎么样?

推荐答案

如果你知道要复制的数据的大小,那么 memcpy() 应该和 一样快或更快strcpy().否则,memcpy() 不能单独使用,strcpy() 应该和 strlen() 后跟 strlen() 一样快或更快代码>memcpy().

If you know the size of the data to be copied, then memcpy() should be as fast or faster than strcpy(). Otherwise, memcpy() can't be used alone, and strcpy() should be as fast or faster than strlen() followed by memcpy().

不过……

memcpy() 和/或 strcpy() 和/或 strlen() 的许多实现旨在有效处理大型数据量.这通常意味着额外的启动开销(例如确定对齐、设置 SIMD、缓存管理等)并使这些实现对于复制少量数据(在编写良好的代码中更有可能)变得糟糕(缓慢).因此,应该一样快或更快"并不一定意味着一样快或更快".例如,对于少量数据,针对大量数据优化的 memcpy() 可能比未针对大量数据优化的 strcpy() 慢得多.数据.

A lot of implementations of memcpy() and/or strcpy() and/or strlen() are designed to efficiently handle large amounts of data. This often means additional startup overhead (e.g. determining alignment, setting up SIMD, cache management, etc) and makes these implementations bad (slow) for copying small amounts of data (which is far more likely in well written code). Because of this, "should be as fast or faster" does not necessarily imply "is as fast or faster". For example, for small amounts of data an memcpy() optimised for large amounts of data may be significantly slower than a strcpy() that wasn't optimised for large amounts of data.

另请注意,这里的主要问题是无法针对特定情况优化通用代码(例如 memcpy()strcpy()).最好的解决方案是拥有多种功能 - 例如memcpy_small() 针对复制少量数据进行了优化,memcpy_large() 针对失败的错误代码进行了优化,避免复制大量数据.

Also note that the main problem here is that generic code (e.g. memcpy() and strcpy()) can't be optimised for a specific case. The best solution would have been to have multiple functions - e.g. memcpy_small() that's optimised for copying small amounts of data and memcpy_large() that's optimised for bad code that failed avoid copying a large amount of data.

这篇关于memcpy() 通常比 strcpy() 快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆