使用memcpy vs直接方法复制结构数组 [英] Copying array of structs with memcpy vs direct approach
问题描述
假设pp是一个指向长度为n的结构体数组的指针. [动态分配] 假设我想通过以下方式创建该结构数组的副本并为其创建一个指针:
Suppose pp is a pointer to an array of structs of length n. [was dynamically allocated] Suppose I want to create a copy of that array of structs and make a pointer to it, the following way:
struct someStruct* pp2 = malloc(_appropriate_size_);
memcpy(pp2, pp, _appropriate_length_);
我还可以进行循环并为0 <= i <= n
做pp2[i]=pp[i]
.
I also can make a loop and do pp2[i]=pp[i]
for 0 <= i <= n
.
这些方法之间有什么区别,哪个更好,为什么?
What is the difference between these approaches, and which is better and why?
推荐答案
对于所有体系结构都没有明确的答案.您需要进行分析以找出最佳方法.
There is no definitive answer for all architectures. You need to do profiling to figure out what method is best.
但是恕我直言,我想想memcpy
会更快,因为有人花了一些时间在您的特定体系结构/平台上,并且能够使用特定的细微差别来加快处理速度.
However IMHO I would imagine that memcpy
would be faster simply that somebody has taken the time for your particular architecture/platform and is able to use particular nuances to speed things up.
这篇关于使用memcpy vs直接方法复制结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!