Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlan Mattanó
Courses Plus Student 12,188 PointsTo Nick Pettit: For optimization purpose is it better to declare variables outside Update or LateUpdate method?
[To: Nick Pettit]
Hi Nick, Looking the video "Creating a New Component" https://teamtreehouse.com/library/components-in-unity/adding-new-behavior/creating-a-new-component
You Declare the float and Vector 3 inside the LateUpdate method. Is this also a good practice ? When is better to declare the variables outside the function or Update? or For optimization purpose is it better to declare variables outside Update or LateUpdate method? Thanks for the course!
1 Answer
Nick Pettit
Treehouse TeacherHi Alan,
Great question! When you declare a variable, there is some overhead. Because of that, declaring the variables every run of Update() or LateUpdate() might seem like a bad idea.
However, the amount of overhead for primitive variables like ints or floats is extremely minimal. Even things like Vector3 or a Quaternion are similarly minimal, because they're just structs that collect these primitive data types.
It's best programming practice to declare variables in the most local scope that you can. In this case, those variables are only needed inside that method, so we can create them and then allow them to be destroyed once the method is done running.
There are a few exceptions to these guidelines. For example, if you have a class of your own design with a complicated constructor method - in other words, a class that requires lots of pre-processing code to run in order for the object to be instantiated - then it would be a bad idea to create one of those complex objects every frame or every physics update. For these simple variables though, it's much more readable and easier to work with when the variables are locally scoped, even though it does add a (very) tiny amount of performance overhead that could be avoided.
Alan Mattanó
Courses Plus Student 12,188 PointsAlan Mattanó
Courses Plus Student 12,188 PointsThanks for the great explanation! Now my code is much simpler and readable.