结构副本与成员副本(省时)

时间:2018-12-03 09:42:48

标签: c performance structure

我们知道我们可以通过分配将一个结构直接复制到另一个结构。

struct STR
{
   int a;
   int b;
};
struct STR s1 = {4, 5};
struct STR s2;

方法1:

s2 = s1;

会将s1分配给s2。

方法2:

s2.a = s1.a;
s2.b = s1.b;

就时间效率而言,哪种方法更快?或两者都需要花费相同的时间进行操作。考虑数据处理的大结构方面!

1 个答案:

答案 0 :(得分:4)

基本上,您无法确定,因为它取决于编译器,目标体系结构等。

但是,对于现代C编译器,启用优化功能后,它们通常是相同的。例如,最近的x86-64上的GCC会为两者生成完全相同的代码:

for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(0, studentRegistration);
            }

产生:

for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                StudentRegistration studentRegistration = postSnapshot.getValue(StudentRegistration.class);
                mChildrenList.add(studentRegistration);
            }