What is the most efficient way to pass/return structs in functions?

Noobish programmer question. For example, should we be defining functions like this?

FMyGameStruct GetGameStructInfo(FAnotherGameStruct data);

…or this?

void GetGameStructInfo(const FAnotherGameStruct& data, FMyGameStruct& outValue);

I see a mix of these approaches in code with FVector, for example.

i’m not good in C++ so i’m not sure about sintax, but looks like your doubt is: what is better, return the struct in the “default return” (1º) or passing a parameter by reference so it will be modified inside the function…
i’ve had the same doubt before while i was learning C, both works, the second one is considered “harder to understand” because usually you expect the output to come in the return instead of passing it through reference, also it may not be clear that the second parameter is the “output” of the function, so i recomend you using the first one, the main use of the 2º approach is when you need to return multiple parameters (which is not the case in your example).
my teacher always recommended me using the first one unless it’s not possible to.

if you wan’t to know more here is a link to a discussion about it in stackoverflow:

Short answer, the second one. Here are the reasons:

Anything that is larger than a primitive will be slower when copying into and out of the function scope. That is why FMyGameStruct GetGameStructInfo(FAnotherGameStruct data); with its two copies of the struct, i.e. data and the return value, is slower than sending everything by reference or by pointers. When you enter the function you copy all the data inside the struct and into the variable data and when you return you return a new copy of the struct inside the function.

For vectors with only 3 primitives the cost for copying over refering is only 3x so many reasons can outweigh the extra cost.


Thanks, NoobsDeSroobs!

Just curious…what would be an example of a reason NOT to pass in a reference to FVector? Why wouldn’t you always avoid the extra cost of copying the 3 primitives?

Thread safety, no intention of returning to the function, the vector needs to be mutable, decoupling from your code(e.g. engine calls).