Lets say i want to create an 90 degree vector on Y Axis every frame,
Is it better to create Vector3.Up * 90;
or new Vector3(0,90,0);
If it was a single frame which one is friendly for memory?
my opinion is:
static variables of Vector3 struct creating once i think its better for memory. Anybody tested or know?
Good question. See for yourself here
This code:
public class C {
Vector3 Method1 () => new Vector3(0,90,0);
Vector3 Method2 () => Vector3.up * 90f;
Vector3 Method3 () => MyVector1;
public static Vector3 MyVector1;
}
public struct Vector3 {
public float x, y, z;
public Vector3(float x, float y, float z){ this.x = x; this.y = y; this.z = z; }
public static Vector3 up => new Vector3(0,1,0);
public static Vector3 operator *(Vector3 vec,float f) => new Vector3(vec.x*f,vec.y*f,vec.z*f);
}
Generates this asm (the only code that your cpu understands):
C.Method1()
L0000: xor eax, eax
L0002: mov [edx], eax
L0004: mov dword ptr [edx+4], 0x42b40000
L000b: mov [edx+8], eax
L000e: ret
C.Method2()
L0000: xor eax, eax
L0002: mov [edx], eax
L0004: mov dword ptr [edx+4], 0x42b40000
L000b: mov [edx+8], eax
L000e: ret
C.Method3()
L0000: push esi
L0001: mov esi, edx
L0003: mov ecx, 0x11a9c608
L0008: xor edx, edx
L000a: call 0x0ff15760
L000f: mov eax, [eax]
L0011: mov edx, [eax+4]
L0014: mov [esi], edx
L0016: mov edx, [eax+8]
L0019: mov [esi+4], edx
L001c: mov edx, [eax+0xc]
L001f: mov [esi+8], edx
L0022: pop esi
L0023: ret
You can see that Method1
and Method2
both ended up looking the same, but Method3
generates more work for the cpu.
Hey there,
if you know you will need this often then do it like this:
public class SomeClass {
public static readonly Vector3 upVector90 = new Vector3(0, 90, 0);
}
From my understanding it will be the best solution regarding performance as it only calculates this vector once and only takes up memory for one.
While it is in general not bad to keep an eye on this you should not focus too much on these kind of micro optimizations unless you are in need of getting every so little last drop of performance out of this. (Which i doubt since you would probably use jobs and float3 otherwise)
These kind of optimizations can take up a lot of time and stagnate your project without actually progressing it in a really meaningful way.