T
T
th0m4sXD2017-09-13 14:58:36
Unity
th0m4sXD, 2017-09-13 14:58:36

Reusing variables?

For example, I have a method

Vector2 getSomePoint(){
    return new Vector2(x,y);
}

So, instead of creating a new Vector2 object, is it better to declare one constant and change its value and then return it in order to avoid frequent calls to the garbage collector, or write as in the code above and it doesn't matter?
I myself think that it is better not to create a new object every time, but in many tutorials they do this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Kormishin, 2017-09-13
@th0m4sXD

Vector2 is a value-type, structure, it is allocated either in the memory of the aggregating object or on the stack.
new in C# doesn't mean it's a heap allocation.
Write as you wrote, everything is in order.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question