Does struct
with a single member have the same performance as a member type (memory usage and speed)?
Example:
This code is a struct
with a single member:
struct my_int
{
int value;
};
is the performance of my_int
same as int
?
Does struct
with a single member have the same performance as a member type (memory usage and speed)?
Example:
This code is a struct
with a single member:
struct my_int
{
int value;
};
is the performance of my_int
same as int
?
Agree with @harper overall, but watch out for the following:
A classic difference is seen with a "unstructured" array and an array in a structure.
When calling functions ...
In some cases, the ABI may have specific rules for returning structures and passing them to functions. For example, given
calling
f
org
may, for example, passa
in a register, and passb
on the stack. Similarly, callingg
may use a register for the return value, whereas callingf
may require the caller to set up a location wheref
will store its result.The performance differences of this should normally be negligible, but one case where it could make a significant difference is when this difference enables or disables tail recursion.
Suppose
g
is implemented asint g(int a, struct S b) { return g(a, b).m; }
. Now, on an implementation wheref
's result is returned the same way asg
's, this may compile to (actual output from clang)However, on other implementations, such a tail call is not possible, so if you want to achieve the same results for a deeply recursive function, you really need to give
f
andg
the same return type or you risk a stack overflow. (I'm aware that tail calls are not mandated.)This doesn't mean
int
is faster thanS
, nor does it mean thatS
is faster thanint
, though. The memory use would be similar regardless of whetherint
orS
is used, so long as the same one is consistently used.If the compiler has any penalty on using structs instead of single variables is strictly compiler and compiler options dependent.
But there are no reasons why the compiler should make any differences when your struct contains only one member. There should be additional code necessary to access the member nor to derefence any pointer to such an struct. If you don't have this oversimplified structure with one member deferencing might cost one addtional CPU instruction depending on the used CPU.