- Home /
Does making a new Vector3() have an impact on performance?
There are time where I need to modify a vector, like "GameObject.Transform.position". For something that runs each frame, does it make a difference if I make a new vector each time, like this: "GameObject.Transform.position = new Vector3(1, 1, modifiedValue);"
or i avoid making a new vector each time, by doing this before the update frame: "Vector3 v = new Vector3();"
then this in the update:
"v = GameObject.Transform.position; v.z = modifiedValue; GameObject.Transform.position = v;
Answer by maormenashe · Feb 10, 2020 at 11:10 AM
I guess when you say "by doing this before the update frame" you mean having it as a member of the class.
Since Vector3 is a struct it will go on the stack depends on the scope you're using it, if you use it as a member of a class which is a reference type then you'd have it saved on the heap, if you're initializing a new instance in a method scope then it will recreate it each time on the stack.
So considering that, and your specific case, yes, it would be better performance wise to use it as a member. In your specific case you'd barley be able to see any difference since the performance impact is very small!
Answer by Klarax · Feb 10, 2020 at 09:39 AM
probably not to the point where its an issue (depending on your game of course)
why cant you define it at the top of script and use it when needed?
C# requires a new Vector3 because it can't modify the transform's property values directly. It would be easier in this case to use Translate
That requires you to have another Vector, but it doesn't mean you need to create it afresh on every frame. v.x=x; v.y=y; v.z=z;
doesn't create a new Vector so something like the OP's own suggested alternative would avoid it too.
@$$anonymous$$larax that's exactly the solution they're proposing - the question was whether or not it makes any difference.
Answer by Aka_ToolBuddy · Jun 09, 2020 at 07:49 PM
Yes, it makes a difference. If you want a more detailed answer, with comparison of IL instructions, take a look at this thread: https://forum.unity.com/threads/vector3-and-other-structs-optimization-of-operators.477338/
Your answer
Follow this Question
Related Questions
Strange New Expression Error, with regards to Vector3 0 Answers
I'm used to Java/Processing, some help with new() please 2 Answers
problem with ScreenToWorldPoint (keep getting the same coordinates) 1 Answer
Quaternion.FromToRotation() 3D direction on 2 axes. 1 Answer
How do I rotate a Vector3 based on two other Vector3? 2 Answers