Vector2 a; vs Vector2 a = new Vector2();

In Unity’s optimization page it mentions try to avoid “new” within a function. Consider the following examples:

void Function1
{
    Vector2 a = new Vector2(1, 1);
}

vs

void Function2
{
    Vector2 a;
    a.x = 1;
    a.y = 1;
}

Are both functions generating garbage every time they are called?

Best to conform this hypothesis, is to put both cases in for loop of let say 100k iterations. And see what profiler will tell you. Just ignore results directly at program startup.

Neither given method generates garbage. Vector2 is a struct. Struct locals will get allocated on the stack, which does not generate garbage.

The “optimization” part comes in because new Vector2( 1, 1 ) is a function call. Function calls do cost cycles, and so are technically slower than no function call.

However, in practice, this difference is not something you should be worrying about unless it is actively causing performance issues.

The “avoiding new in a function” is referring to classes, which get allocated on the heap. Essentially what it’s saying is that you should be careful of your allocations, since too much GC will cause stutter.

3 Likes