Local variables versus instance variables

I have done a lot of research on optimizing C # for a game that I create using XNA, and I still don't quite understand if local variables are instance variables, improving performance with constant updating and usage.

According to http://www.dotnetperls.com/optimization, you should avoid parameters and local variables, which means that instance variables are the best option in terms of performance.

But some time ago I read in another StackOverflow record (I can’t find where it was) that local variables are stored in that part of the memory where it is faster to access, and that every time the instance variable, the previous value should be deleted as a tedious extra step before a new value is assigned.

I know that from a design point of view, it can break encapsulation in order to use instance variables in such a situation, but I'm strictly interested in performance. Currently, in my game, I pass local variables into 3 of 7 methods in the class, but I could easily push variables into instance variables and be able to completely avoid passing parameters and local variables.

So what would be better?

+5
source share
3 answers

Are your reference positions variables (class or string) or values ​​(struct)?

For reference types, there is no significant difference between passing them as an argument to a method and holding them in an instance of an object. In the first case, when entering a function, the argument will (for functions with a small number of arguments) fall into the register. In the second case, the link exists as an offset of the data indicated in memory to 'this'. Any scenario is a quick capture of a memory address and then retrieving the associated data from memory (this is the expensive part).

( , ). , , 'this'. (DateTime structs ), , .

, ( ). .NET( ), - , . , ( ).

+2

( struct s). , GC XNA, , , .

-local, ( ) . - , .

, ( , ).

, , , ...

, , , - , .

, .

+1

, ( ) .

, , , , , , ( ) .

, , - , . , , C/++ #. , , .

This prevented the allocation of memory for new objects, the initialization of new objects, and often the system would be almost the same, so I would only have to modify the small bits to update it.

Usually, before you do any kind of optimization, do you want to make sure that you are optimizing something that will significantly affect overall performance?

+1
source

All Articles