Pergunta

I am learning C and would like to ask about best practices.

Here two implementations (shirt is struct):

implementation1 :

void printShirt(shirt shirt){
    printf("(%d , %s)",shirt.size,shirt.color);
}
void printShirts(shirt * shirts, int nbShirts){
    int i;
    for(i=0;i<nbShirts;i++) printShirt(shirts[i]);
    printf("\n");
}

implementation 2:

void printShirt(shirt * shirt){
    printf("(%d , %s)",shirt->size,shirt->color);
}
void printShirts(shirt * shirts, int nbShirts){
    int i;
    for(i=0;i<nbShirts;i++) printShirt(&shirts[i]);
    printf("\n");
}

If I am correct (?), in implementation 1 the data of each shirt is copied from heap to stack before print. But this does not happen in implementation 2 (?).

For big arrays and structure might this have an impact ? Is there some best practice to follow ?

Foi útil?

Solução

Yes, this can have an impact on large structures, or large arrays of smaller structures, unless the compiler is able to optimize the call away. It's far more normal to avoid copying data when you already have a copy of it - especially if you aren't intending to modify the copy.

Copying a struct is quite fast - it essentially just blits bytes from one location in memory to another... But copying a pointer is faster. If the struct is small, you might consider copying it so that you avoid extra pointer dereferencing. However, by now you may well be getting into premature optimization.

Back to the pointer approach, normally you help the programmer to realise that the data will not be modified by receiving a const pointer:

void printShirt( struct shirt const * shirt )

Your example is a bit naive, because the cost of printf is far greater than copying even a relatively large structure. But I understand what you're trying to ask.

Outras dicas

You will use less memory the implementation 2 since you only pass in the address (pointer) to the printShirt function. Implementation 1 could be slow if sizeof shirt is big and it will also consumes more memory since you're going to copy all fields in the struct.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top