Search Unity

Does Passing Controls by Reference Improve Performance?

Discussion in 'Input System' started by ordowerm, Jan 14, 2022.

  1. ordowerm

    ordowerm

    Joined:
    Mar 6, 2018
    Posts:
    6
    Hi, folks!
    I'm coming from a C++ background, and I'm accustomed to including pointers as fields in my objects, as opposed to a fully-instantiated object on the stack.

    I also struggle when reading documentation sometimes; please forgive me if this is answered in "official" references/manuals/scripting documentation.

    Suppose I've exported my input action map into a public class called Controls.
    Suppose I'm using an FSM to control the character. The FSM instantiates different states on Awake, and each state needs access to those controls.

    Code (CSharp):
    1. public class PlayerState
    2. {
    3.       protected Controls controls;
    4.       protected Rigidbody rb;
    5.    
    6.       public PlayerState(in Controls c, ref rb)
    7.       {
    8.           controls = c;
    9.       }
    10.  
    11.      protected virtual void GetInput()
    12.      {
    13.       //include stuff here
    14.      }
    15.  
    16.      /*
    17.      * Miscellaneous methods here
    18.      */
    19. }

    Code (CSharp):
    1. public class PlayerStateMachine : MonoBehaviour
    2. {
    3.      public Controls controls;
    4.      public Rigidbody rb;
    5.      protected PlayerState state0;
    6.  
    7.      /*
    8.      * other states, miscellaneous fields, etc.
    9.      */
    10.  
    11.      protected Awake()
    12.      {
    13.            state0 = new PlayerState(in controls, ref rb);
    14.        
    15.            /*
    16.            * Initialize other states, other fields
    17.            */
    18.      }
    19.  
    20.      /*
    21.      * other methods here
    22.      */
    23.  
    24. }

    Main Questions:
    (1.) Does it save memory to use the "in" keyword here?
    (2.) Does it save memory to use the "ref" keyword here?
    (3.) Is this a misguided way of handling this stuff? If so, why?


    I recognize that I could use the profiler to test this, but I'm not confident using it yet, and I'd have to set up the testing, when I suspect y'all might know the answers off the top of your heads.