简体   繁体   English

类VS ref Struct

[英]Class VS ref Struct

I am programming a game using C#, thus, I am very concerned about performance. 我正在使用C#编写游戏,因此,我非常关注性能。

I would like to know what are the main differences, and if possible, performance considerations of using either a Class to pass data around, or a struct passed by reference. 我想知道主要区别是什么,如果可能的话,使用Class传递数据或通过引用传递的struct的性能考虑。

I wish not to copy the data around, for performance reasons (I assume passing by ref is much faster than by value here). 出于性能原因,我希望不要复制数据(我假设通过ref传递比这里的值快得多)。

I know that a class is always passed by reference and that a struct is passed by value, but I talking about passing the struct by reference here. 我知道一个类总是通过引用传递,并且结构是通过值传递的,但我在谈论通过引用传递结构。

An example of the data I wish to pass : 我希望传递的数据示例:

    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, would using a class make a difference? 在前面的例子中,使用类会有所作为吗? If so, what would the difference be? 如果是这样,差异会是什么? Would a class be faster than a struct in this example? 在这个例子中,一个类是否比结构更快? Why? 为什么?

Thank you. 谢谢。 Joao Carlos 若昂卡洛斯

I know that a class is always passed by reference and that a struct is passed by value, but I talking about passing the struct by reference here. 我知道一个类总是通过引用传递,并且结构是通过值传递的,但我在谈论通过引用传递结构。

You probably have the right idea, but this is incorrect. 你可能有正确的想法,但这是不正确的。 Everything in C# is passed by value unless you use the ref keyword. 除非使用ref关键字,否则C#中的所有内容都将按值传递。

Class instances are reference types, struct instances are value types. 类实例是引用类型,结构实例是值类型。

When you pass a reference type by value, you pass a copy of the reference (small). 按值传递引用类型时,将传递引用的副本(小)。 When you pass a value type by value, you pass a copy of the whole data (potentially large). 按值传递值类型时,将传递整个数据的副本(可能很大)。

Jon Skeet has a good explanation of all this here . 乔恩斯基特拥有的这一切很好地解释了这里

Your delegate receives a reference type - a List , so you're passing the entire list by reference anyway. 您的代理人会收到一个引用类型 - 一个List ,因此您无论如何都要通过引用传递整个列表。

Passing a large structure by value is definitely most expensive than passing just the reference. 按值传递大型结构绝对比仅传递引用最昂贵。 When you have a large structure, it usually doesn't make sense to use it as a structure, just turn it into a class. 当你有一个大型结构时,将它用作结构通常没有意义,只需将其转换为类。

Anyway, are you sure you'll have a performance issue here? 无论如何,你确定你会遇到性能问题吗? Seems like a very premature optimization. 似乎是一个非常不成熟的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM