C# Vector3 creation performance

Does creating a new Vector3 in a loop affects performance? How is C# or the compiler handling it?

For example, if I have to instantiate objects based on a grid (10x10) and every one has a different position, does creating a new Vector3 for each position affects performance? I’m just curious, because as afraid as I am, I always try to create only one Vector3 object at the outside of the loop and change its values on the loop, thus reusing the object.

Any of you know if this is necessary or the compiler is automatically doing it for me?

Update!

Code (based on Arowx)

using UnityEngine;
using System.Collections;
public class V3test : MonoBehaviour {
	// Use this for initialization
	void Start () {
		
		int size = 999999;
		
		float s;
		float e;
		
		Vector3 vectToSet;
		
		/////////////////////////////////////////////  In Loop
		
		s = Time.realtimeSinceStartup;
		
		for (int i = 0; i < size; i++) {
			vectToSet = new Vector3(1,1,1);
		}
		
		e = Time.realtimeSinceStartup;			
		e -= s;
		
		Debug.Log("In Loop: "+e.ToString() + " seconds" );
		
		///////////////////////////////////////////// Outside Loop
		
		s = Time.realtimeSinceStartup;
		
		Vector3 newVect = new Vector3(1,1,1);
		for (int i = 0; i < size; i++) {
			vectToSet = newVect;
		}
		
		e = Time.realtimeSinceStartup;			
		e -= s;
		
		Debug.Log("Outside Loop: "+e.ToString() + " seconds" );
		
	}
	
}

Results (with Int.MaxValue iterations)

Test 1

In Loop: 24.32912 seconds
Outside Loop: 10.66983 seconds

Test 2

In Loop: 24.3905 seconds
Outside Loop: 10.65773 seconds

Setup

Test it… [Shouldn’t be a problem though - using structs in loops is a fairly normal operation and therefor should be well optimized. Remember - structs are immutable.]

Isn’t that the whole big thing with object oriented programming- er…something like that??

I have no idea what you’re talking about.

I’ll just reiterate what NPSF3000 said : test it and see yourself. Then let us know the results!

I may be entirely wrong, but I think the memory is allocated to those variables the first time they are initialised, then after that the variable is just written over. Although it is technically messy to be creating variables in an Update loop, but I don’t think you will find a noticeable performance loss.

Test it and see!

In actual fact creating a new Vector3 and unrolling the operations is nearly twice as fast as using vector to vector operations http://forum.unity3d.com/threads/108052-Vector3-Profiling-and-Optimising-Unrolling-x-y-z-faster-than-v3-op-v3.

From your example depending on usage it could be faster to create a 3D array to store the x,y,z but it’s always best to do a test of these things and with a harness that mimics how they would actually work and then decide but currently in Unity xyz calculations appear to be nearly twice as fast as vector operations.

Hopefully Unity will bring some optimisations to this in the next release (fingers crossed)!

Creating 100 vectors is done in a flash, no matter how you do it. Write clear code first and worry about performance later if it becomes an issue. Most likely this is not going to be your bottleneck.

Having said that, reusing a struct variable instead of invoking new ones in a loop basically saves you one method call per iteration (which pushes three floats plus the resulting struct and assigns floats).

The C# compiler has a lot of subtleties that vary by version, but most of the time you shouldn’t worry about it because stuff like which lighting model you use make a far bigger inpact.

This is true except in a case where the object behind the variable is immutable.

I don’t see any reason why this would cause performance issues. In some of my Import-Export work I’ve been generating hundreds of Vector3s for vertex positions and it does it very quickly.

Thanks for the advice! I’ve updated the original post with my results. Is there any way to test the memory? I know if we create 99999 new Vector3 it will be garbage collected eventually… But I just wanted to test it because as stated, I’m curious.

It’s a local instance of a struct, allocated on the stack; there’s no garbage collection.

–Eric

Hi Eric, I was reading a little about immutable structs, so what you said means that:

Vector3 myVect = new Vector3(1,1,1);

Is kinda the same as:

int myInt = 1;

?

By that, I mean that they end up being treated like values.
Looking at the example (in the original post), we have a loop of 999999 iterations assigning new Vector3’s to a single Vector3. In this case, and if I understood correctly, there’s only 1 Vector3 allocated, vectToSet. Is this right?