How do I pass a structure to a function?

I am confused because I haven't written C in a while. In C ++ we will pass them as references so as not to copy the whole structure. Does this apply to C too? Should we pass them as pointers even if we don't want to modify them to avoid copying?

In other words, for a function that checks if two structures are equal, it is better to do

int equal(MyRecord* a, MyRecord* b);

and decrease readability a bit (due to pointers)

or

int equal(MyRecord a, MyRecord b);

will have the same performance?

+3


source to share


3 answers


Which is faster in bulk depends on the size of the structure and its use within the called function.

If your structure is not larger than a pointer, pass by value is a better choice (less or equal amount of data must be copied).



If your struct is larger than a pointer, it depends heavily on the type of access that happens inside the called function (and obviously also on the ABI specifics). If many random accesses are made to the structure, it may be faster to pass a value, even if it is larger than a pointer, due to the indirection of the pointer within the function.

In general, you need to profile to figure out which is faster if your struct is larger than a pointer.

+3


source


Often times pointer traversal is faster - and you call equal(&r1, &r2)

where r1

and r2

are local variables struct

. You can declare formats as const

pointers to a structure const

(this can help optimize the compiler to generate more efficient code), You can also use a keyword restrict

(if you are sure that you will never call yours equal

two identical pointers, for example equal(&r1,&r1)

, i.e. without pointer aliasing ).

However, some special ABIs and calling conventions may mandate specific handling for some individual structures. For example, the x86-64 ABI for Linux (and Unix SVR4) says it returns struct

with two pointers or integers across two registers. This is usually faster than changing a memory zone with its pointer in a register. YMMV.



To find out which is faster, you really need to navigate. However, passing large enough struct

(for example, with at least 4 integral or pointer fields) in value is almost always slower than passing a pointer to it.

By the way, what's really important for modern desktop and laptop processors is the CPU cache . Storing frequently accessed data inside an L1 or L2 cache will improve performance. See also .

+6


source


Passage pointers are faster, for reasons you tell yourself.

In fact, I find C more readable than C ++, in this case: by passing a pointer in the call, you are confirming that your parameters can be changed by the called function. With C ++ references, you cannot immediately tell that by seeing only the call, you should also check the prototype of the function being called to see if it is using references.

0


source







All Articles