Declaring variable type in class state vs update method

Hey there,

I’ve been wondering if there is a performance difference in these 2 cases:

  • Variable type is declared in the Class state

  • Variable type is declared in Update() method

I’ve seen a lot of cases where people tend to declare a variable type inside Update() method. I’m not experienced C# dev but it seems to me that variable type should only be set once and every other time only value of the variable should be updated? Is there some kind of caching system that resides in the background that handle this kind of stuff that I’m not aware of?

You may want to revisit the documentation on ‘local variables’ and ‘variable scope’. Programmers tend to re-use transient variable names like i, j, k, n, index, count etc. and define them locally. The ‘scope’, i.e. the part of code where these variables are valid is usually limited to the block they are defined in, and they usually override variables of the same name that were declared in an outer scope. So if a programmer declares a vairable ‘i’ at class scope, they can also re-declare a variable ‘i’ inside a method. Accessing ‘i’ will Default to accessing the most narrow scope, i.e. the one just declared, and leave other same-Name variables untouched.

None of this has to do with Performance, though, and you should not concern yourself with performance issues at this level - if you have perfromance issues, use the profiler to home in on cycle criminals.