is there a point in recycling value types unity
c#, heap-memory, optimization, stack-memory, unity-game-engine
Solution
This is fairly dependent on what you wish to do with this object.
Lets take your first example, say we would want to access the variables x & v from a second function `functionCalledEveryOnceSoOften()` This function won't need any overloads to pass the variables, and can just directly access the variables in the instance of the class.
With the second example, if we wanted to do the same thing. We would have to call `functionCalledEveryOnceSoOften(int, vector3)` As the function would not have direct access to the variables.
In unity it is often the case that a function will need to use the same values as another function, all though they might not always be called in chain's. To accommodate this in your 2nd example, we would have to add `if` statements inside our function to filter this out.
In your first example however, we could use these variables without a issue. This is one of the reasons it is often advised to do so.
As per the performance, in your 2nd example the variable is stored in the stack as opposed to the heap, because it is defined within the confines of a method which will get destroyed once the method ends executing. So the variable's memory usage is not really a concern. There might be a small overhead for the repeated creation and destruction, but this should be insignificant.
In your first example you will store the variable on the heap, as it is defined within the scope of the class, it will only be destroyed along with the class, and created on it's instantiation. This means that memory might be used over longer periods of time, but there will be no overhead for creating/destroying the variable. This also is usually insignificant.
All together, unless you are instantiating thousands of these objects, accessing the variables in rapid succession you will most likely not notice a lot of difference in performance.
The biggest difference will most likely be the way code is written. For better, or for worse.
Problem
I found article stating that recycling and reusing variables is good practice in unity. So I adopted it. But one thing not clear : does this apply to value type variables (integers, vectors)? is there a point i using this: ``` int x; Vector3 v; void functionCalledVeryOften(){ x=SomeCalculation(); v=SomeCalc(); //do something with x and v } ``` instead of this: ``` void functionCalledVeryOften(){ int x=SomeCalculation(); Vector3 v=SomeCalc(); //do something with x and v } ```