Ginu Jacob
Ginu Jacob

Reputation: 1798

Efficiency of struct copying

When copying between two structure variables in C, in the back-end whether it does a memcpy or an item by item copy? Can this be compiler depended?

Upvotes: 1

Views: 312

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148965

You should not even think about that. Compilers are only required that the observable results of what they generate are the same as would you asked. Besides that, they can optimize the way they like. That means that you should let the compiler choose the way it copy structs.

The only case when the above rule does not apply it in case of low level optimization. But here other rules apply:

  • never use low level optimization at early development stages
  • only do after identifying by profiling the bottlenecks in your code
  • always use benchmarking to choose the best way
  • remember that such low level optimization only make sense for one (version of) compiler on one architecture.

Upvotes: 1

Serve Laurijssen
Serve Laurijssen

Reputation: 9753

It's heavily compiler dependant

Consider a struct with just 2 fields

struct A { int a, b; };

Copying this struct in VS2015 in DEBUG build generates the following asm.

struct A b;

b = a;

mov         eax,dword ptr [a]  
mov         dword ptr [b],eax  
mov         ecx,dword ptr [ebp-8]  
mov         dword ptr [ebp-18h],ecx  

Now added an array of 100 char and then copy that

struct A
{
    int a;
    int b;
    char x[100];
};

struct A a = { 1,2, {'1', '2'} };
struct A b;

    b = a;

mov         ecx,1Bh  
lea         esi,[a]  
lea         edi,[b]  
rep movs    dword ptr es:[edi],dword ptr [esi]  

Now basically a memcpy is done from address of a to address of b.

It depends on a lot of the layout of the struct, the compiler, the level of optimization...a lot of factors.

Upvotes: 5

Related Questions