8
\$\begingroup\$

I'm using Unity and sometimes I'm using th new keyword in Update, like new Vector3() etc...

I wonder is this causes memory leak? I mean in every frame a new Vector3 is created. If this is the way of working that means there are thousands of Vectors created in memory. Is it true or do I think wrong?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ This sounds like a question from a typical C++ user who isn't familiar with the ins and outs of C#, would that be an adequate assumption? \$\endgroup\$
    – Pharap
    Mar 13, 2017 at 22:07
  • \$\begingroup\$ I answered a similar question here. It's fine to do new Vector3 because Vector3 is a struct. If it is a class then that's a problem. Read the whole post about using Object pooling. \$\endgroup\$
    – Programmer
    Mar 14, 2017 at 10:15

1 Answer 1

15
\$\begingroup\$

In C# there are two kinds of types, roughly: value types and reference types.

You use new when you create both, but value types are created on the stack (most of the time), and only reference types get created on the heap. Once created, reference types stick around until the garbage collector happens to come along, determine they are no longer needed, and collects them. Instances on the stack are destroy efficiently when the stack frame goes away (when the function they were created in ends).

Vector3 is a value type in Unity, so almost all the instances you ever create will be stored on the stack and thus cheap to both create and destroy. So you're not likely doing anything wrong here. It certainly doesn't create a memory leak, and it almost certainly won't be a performance issue (you'd want to profile to be sure, anyhow).

Creating a lot of new reference types every frame can be problematic since that can induce the garbage collector to run more frequently, causing hitches as it pauses all your threads to do its work. But value types like Vector3 are a pretty safe bet.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think you should emphasize that "value types are created on the stack (most of the time)" is only true for local variables. I know it's a bit pedantic but the way it's currently worded can mislead beginners. An int field in a reference type ends up on the heap since reference types are stored on the heap. That aside, +1 \$\endgroup\$
    – Doval
    Mar 14, 2017 at 4:55
  • 2
    \$\begingroup\$ @Doval a much more accurate statement would be that "value types get put in previously allocated space like on the stack or inside the allocated space of a reference type". \$\endgroup\$ Mar 14, 2017 at 10:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .