Class VS ref Struct

I am programming a game using C #, so my performance is very worried.

I would like to know what are the main differences and, if possible, performance considerations when using either a class to pass data or a structure passed by reference.

I want to not copy the data for performance reasons (suppose the ref transfer is much faster than the value here).

I know that a class is always passed by reference and that struct is passed by value, but I'm talking about passing a structure by reference here.

Example data that I want to transfer:

public delegate void PathCompleteDelegate(List<PathFinderNode> path); public struct PathFinderJob{ public PathCompleteDelegate callback; public Vector3 start, end; public PathSize unitSize; public BoxCollider boxCollider; } 

In the previous example, the use of the class will change? If so, what's the difference? Will the class be faster than the structure in this example? Why?

Thanks. Joao Carlos

+6
source share
2 answers

Your delegate gets the reference type - a List , so you still pass the entire list by reference.

The transfer of a large structure by value is certainly the most expensive than the transfer of only links. When you have a large structure, it usually doesn't make sense to use it as a structure, just turn it into a class.

In any case, are you sure you will have a performance problem? Seems like a very premature optimization.

+4
source

I know that a class is always passed by reference and that a structure is passed by value, but I'm talking about passing a structure by reference here.

You probably have the right idea, but this is not true. Everything in C # is passed by value unless you use the ref keyword.

Instance instances are reference types; struct instances are value types.

When you pass a reference type by value, you pass a copy of the help (small). When you pass a value of a type by value, you pass a copy of all the data (potentially large).

Jon Skeet has a good explanation of all of this here .

+7
source

Source: https://habr.com/ru/post/911925/


All Articles