简体   繁体   English

使用可为空的结构能否提高性能?

[英]Could the use of nullable structs improve performance?

I was thinking the following: 我在想以下几点:

Since, structs can improve GC performance and Nullable<T> is a struct itself, would it be better in terms of performance (GC performance or overall) to use a nullable struct instead of a class? 由于结构可以提高GC性能,而Nullable<T>本身就是结构,因此在性能(GC性能或总体)方面使用可空结构代替类会更好吗?

Has anyone experience on this? 有人对此有经验吗?

EDIT: 编辑:

Eg: I was thinking more about creating an options class/struct for a method call: ConvertToPdf(..., MyType options) . 例如:我在考虑为方法调用创建一个选项类/结构: ConvertToPdf(..., MyType options) So, not extra huge structs with many methods or anything like that. 因此,不要使用许多方法或类似方法来构建超大型结构。

No. 没有。

structs .. being the basis for value types, should remain small. 作为值类型基础的structs ..应该保持较小。 Classes don't generally remain small, and so by substituting all uses of a class for a struct .. you will be creating in fact slower runtime speeds.. since value types are copied in their entirety. 类通常不会保持较小,因此通过将类的所有用法替换为struct ..实际上,您将创建较慢的运行速度..因为值类型是完整复制的。

A structure is semantically equivalent to a bunch of variables stuck together with duct tape. 结构在语义上等效于一堆用胶带粘在一起的变量。 If one were to create a structure 如果要创建一个结构

public struct MaybeValid<T>
{
  public T Value;
  public bool IsValid;
}

then the Value field of a variable of a MaybeValid<T> could be worked with just as efficiently as a variable of type T . 那么MaybeValid<T>变量的Value字段可以与T类型的变量一样有效地工作。 The Framework's Nullable<T> isn't defined that way, however. 但是,框架的Nullable<T>并不是这样定义的。 Consequently, it's often necessary to copy the Value of a Nullable<T> to some other variable before anything can be done with it. 因此,通常需要先将Nullable<T>Value复制到其他变量,然后才能执行任何操作。 The extra layers of copying required when using Nullable<T> mean that code using it will generally be nowhere near as efficient as code using other types could be. 使用Nullable<T>时需要额外的复制层,这意味着使用它的代码通常不会比使用其他类型的代码有效。

Premature optomisation! 过早的乐观! - given that possible as you don't get boxing directly as you would wrapping it in a class you can make nullable. -考虑到有可能,因为您不会像将其包装在类中那样直接得到拳击,因此可以将其设置为可为空。 Assuming of course that use of a struct is appropriate - you do tend to see a lot of classes with very few members, these could be a target. 当然,假定使用结构是适当的-您的确会看到很多类的成员很少,这些可能是目标。 But you dont want to optomize like this until you know you need to because you are only a mortal. 但是在您知道自己需要这么做之前,您不希望这样自欺欺人,因为您只是凡人。

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

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