Hi guys,
My game’s physics requirements mean that I have to perform a set of Vector3 ops (add, multiply, normalise and divide) around 3000 times a second which as you could imagine creates quite a large overhead. I have read that Unity uses properties to access the x,y,z components of the vector as well which aren’t the fastest things around and looking at the code, there is a lot of new memory being declared for performing addition/multiplication etc.
Has anyone implemented their own Vector3 struct in Unity?
Looking at what code exactly? Also, how are you determining that memory is being declared?
I just used reflector to look through the Vector3 struct. Now there may be no other way to perform the ops but here’s an example of the addition op:
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
Instead of returning a new Vector3, could the class have a static vector3 that is just used for performing the op or am I missing something? Either way the performance I’m getting is very slow, with the profiler saying all the time is used in the addition and normalize functions
That memory will be stack-allocated, so it shouldn’t involve the GC at all, if that’s your concern.
Performing large numbers of normalizations or other vector operations on a per-update basis could have an impact on performance, I’d imagine. That said, I’d look at possible high-level optimizations before worrying about the performance of Vector3.
Can you tell us anything about the context? What are you simulating? Where are all those vector operations going?