Search Unity

How do you know when to keep reference or get when needed?

Discussion in 'Scripting' started by Unlimited_Energy, Oct 4, 2020.

  1. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469
    I'm wondering as best practice for coding games, when do I choose to keep a references to something as opposed to use GetComponent<> inside a method? I know storing references uses more memory but I know getting references inside a method creates garbage when it is disposed. I know it depends on how often it gets called matters(like something in update loop you'd want a cached reference as opposed to get component every frame) but what to do for stuff that's in between being referenced "fairly frequently"?

    I know its unpredictable sometimes to know when the GC is going to trigger and maybe this is something that developers do later on as they optimize and decide looking at the profiler what should be cached reference vs temporary reference that will be disposed? Just wondering if, while programing, I should be deciding on permanent reference vs temporary when its use is not every frame or even every minute, but could be called hundreds of times a game session for example.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    In practice Unity and modern computers are a BEAST combination, and you can get away with an awful lot before you have a problem.

    If you encounter performance problem, the only way to begin is to open the profiler (Windows -> Analysis -> Profiler) and figure out what is causing the problem.

    Best practices says do not make optimizations for problems you speculate you might have.

    Best practices says get references at Start(). But that can get messy with a lot of things that are only rarely used.

    One reference is going to cost you only a few bytes. Computers have hundreds of megabytes of RAM available, generally.

    Best practices also says your code should be easy to understand if you come back a month later. Weird whacky optimizations can definitely get in the way here.

    I say charge ahead with various things, get comfortable with some, and learn to recognize problematic patterns/approaches.
     
    Unlimited_Energy likes this.
  3. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469
    Thanks appreciate it. I have been caching a reference for anything that's not a couple call here and there.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Unlimited_Energy likes this.