- Home /
Structs passed by ref = better performance?
In .NET passing to a function large struct by ref has a performance gain because they don't have to be copied but instead a reference to the location on the stack is passed. Is it the same for Unity on mobile? I don't see many examples like (ref Vector3 struct) in Unity API
Thanks in advance
When I say large struct I mean for example Vector3 = 4*3 bytes = 12 bytes If passed by ref should take only 4 bytes for the ref
I cannot make Vector3 already to be class. What would be better performance-wise:
1.) Some$$anonymous$$ehtod(Vector3 v)
or
2.) Some$$anonymous$$ehtod(ref Vector3 v)
In .NET for example XNA, clearly 2.) is faster event though 1.) is prerettier
Answer by rutter · Jul 01, 2014 at 11:29 PM
Pass-by-ref does tend to run faster, but isn't always worth the trouble.
Why not use a class, instead? A "large" struct sounds like a possible design problem.
As I understand it the primary difference between a class and a struct is a struct is always passed by value, while a class is always passed by reference.
$$anonymous$$akes sense to me to use a class if you want default pass by reference.
$$anonymous$$atrix4x4 is what I would consider a large struct (16 floats). I can't think of any other common structs in Unity that would be worth passing by reference for performance reasons. Vectors, Color and Quaternions top out at 4 floats which certainly isn't worth the trouble (including losing immutability) for essentially no gain.
If the code is performance critical it makes sense to use struct to optimise memory allocation because they don't need separate heap allocation for every instance and may be allocated in call stack.
Answer by Huacanacha · Jul 01, 2014 at 11:42 PM
A Vector3 is just three floats so it's pretty much pointless, for performance reasons, to pass by ref which requires creating the reference wrapper and dereferencing when used.
You also lose the immutability of the struct which could lead to unexpected consequences. For example grabbing the position of an object then modifying will move the object without explicity setting the transform.position. In many (maybe most) cases this won't be the intent.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Structs in C# Question 3 Answers
Where to use Structs and classes? 5 Answers
Putting user defined struct in Unity Editor 4 Answers
How to declare a struct in C# 1 Answer