• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by FaffyWaffles · Mar 01 at 05:20 AM · optimizationprofilingbest practicesdefinereadable

Which of these two methods is better practice? Defining Variable Inside vs Outside a Method

Between these two example methods, what are the pros and cons of each? Overall, which is the better practice, and why?

     void Foo()
     {
         MeshFilter meshFilter = GetComponent<MeshFilter>();
 
         Mesh mesh = meshFilter.sharedMesh;
         int[] triangles = mesh.triangles;
         Vector3[] vertices = mesh.vertices;
         Vector3[] normals = mesh.normals;
         //Do Stuff
     }


     public MeshFilter meshFilter;
     private Mesh mesh;
     private int[] triangles;
     private Vector3[] vertices;
     private Vector3[] normals;
     void Bar()
     {
         meshFilter = GetComponent<MeshFilter>();
 
         mesh = meshFilter.sharedMesh;
         triangles = mesh.triangles;
         vertices = mesh.vertices;
         normals = mesh.normals;
         //Do Stuff
     }

  • Is there any difference other than Foo() being easier to call from other methods?

  • Which one is better for memory?

  • Which one is better for speed?

  • If either Foo() or Bar() are called with the update method, does that change?

  • Is it more costly to define a variable once and hold it in memory, or to define a variable once per frame?


This isn't homework or anything. I've been coding with C# for a little over 2 years now, and I never really learned the internals of how everything works. This is a question that I've often had, yet never really set out to find the answer.


Also, I know about the "Tragedy of Mirco-Optimization" and "Premature Optimization: The Root of All Evil" stuff. But when I'm writing thousands of lines of code, it starts to add up. More importantly though, I would like the peace of mind that I am in fact using the right method in a given situation.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image FaffyWaffles · Mar 01 at 05:21 AM 0
Share

Also, this is given that MeshFilter always exists and contains a mesh, so to never through a null exception.

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Captain_Pineapple · Mar 01 at 07:53 AM

In general this question is good, but not from a point of optimization, but from the architectural side.


Why not performance: perhaps if you have a few hundred thousand to million objects/calls of this you might see a difference in the micro-millisecond area. You'll have way more other problems before you reach this point so do not expect this to "add up" this fast. It is generally good to keep this in mind but once again: do not try to specifically optimize this if it is not an issue or you know it is going to be one


Regarding the current setup i'd personally recommend this:

 public someComponent : Monobehaviour {     
      [SerializeField]
      private MeshFilter meshFilter;
      private Mesh mesh;
      private int[] triangles;
      private Vector3[] vertices;
      private Vector3[] normals;
      void Awake() {
            meshFilter = GetComponent<MeshFilter>();
      }
 
      void Bar()
      {
          mesh = meshFilter.sharedMesh;
          triangles = mesh.triangles;
          vertices = mesh.vertices;
          normals = mesh.normals;
          //Do Stuff
      }
 }

Here's why:

The by far most expensive call in your example methods i GetComponent. All else is negligable in comparison. Make sure you always cache Component references where possible.

That being said, your point regarding Foo beeing easier to call from other methods is correct, but since Foo is a non-static function you need an object instance to call the function. When you have the object instance there is no need for Foo as Bar from my example would then be just as "easy" to call. Now one could say: sure lets make Foo static, but that does not work as you then cannot use GetComponent.


TL;DR: Don't use GetComponent in reoccuring spaces. Always cache the result in member variables.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

140 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Profiling PostLateUpdate.FinishFrameRendering Causes Major Spikes in Performance for Android Game 0 Answers

EventSystem.Update() takes up 90% of CPU - Profiler Data Help 0 Answers

What do RenderForwardOpaque::Sort/Render/Prepare do? 0 Answers

High iteration shader with blitter blocks cpu 0 Answers

Why does the internal profiler show no GPU usage? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges