Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.