有结构体"快"不是类 - 总体上还是在.NET框架? [英] Are Structs "faster" than Classes - In general or in the .NET framework?

查看:237
本文介绍了有结构体"快"不是类 - 总体上还是在.NET框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于结构是值类型,他们的数据是复制时,传递给方法作为参数。例如:

Since structs are value-types, their data is copied when passed into a method as an argument. Example:

int someInt = 7;

DoSomeMethod(someInt); // <-- This is passing the "value" 7.

到目前为止,容易理解,而你可能想知道我的问题是有效的...所以考虑以下几点:

So far, easy to understand, and you're probably wondering how my question is valid... so consider the following:

public struct TimmysStructOfGoodness
{
    public int SomeInt1;
    public int SomeInt2;
    public int SomeInt3;
    // ... later that day ...
    public int SomeInt999;
}

和然后,参照以下code:

and then, with reference to the following code:

TimmysStructOfGoodness someStructOfGoodness = new blah blah blah...

DoSomeMethod(someStructOfGoodness); // <-- **HERE IS WHERE THE QUESTION APPLIES!**

难道上面的语句尝试分配RAM数兆复制我的价值型(​​结构)?

Does the above statement try to allocate several megs of ram to "copy" my value-type (struct)?

如果答案是肯定的 - 那么当/在哪里的快而行慢

If the answer is yes - then when/where is the line between "faster" and "slower"?

如果没有 - 那么为什么不呢?因为我所知道的价值类型,这应该是一个问题。

If no - then why not? Because what I know of value-types, this should be a problem.

主要免责声明:我知道这个有没有关系,为什么你会使用结构诗句一类的,我知道,我永远不会让一个结构与999字段 - 这是基本的内部和胆量和只是一个问题,类似:)

MAJOR DISCLAIMER: I know that this has nothing to do with why you would use a struct verses a class, and I know that I will never make a struct with 999 fields - this is just a question of underlying internals and guts and the like :)

推荐答案

(更新,感谢捐款来自其他用户)

(updated, thanks to contributions from other users)

不同于类,结构是在堆栈中创建。因此,它是更快实例(和销毁)一个结构不是一个类。

Unlike class, struct is created on stack. So, it is faster to instantiate (and destroy) a struct than a class.

除非(亚当·罗宾逊指出的)结构是在这种情况下,它被分配在堆中的类成员,以及其他一切。

Unless (as Adam Robinson pointed out) struct is a class member in which case it is allocated in heap, along with everything else.

在另一方面,每次分配结构或将它传递给一个函数的时候,它就会被复制。

On the other hand, every time you assign a structure or pass it to a function, it gets copied.

我不认为有一个结构大小的硬性限制。千字节肯定是太多了。 MSDN

I don't think there's a hard limit for a struct size. Thousands of bytes is definitely too much. MSDN says:

除非你需要引用类型   语义,一类是小   大于16字节可以更有效地   通过该系统处理为一个结构。

Unless you need reference type semantics, a class that is smaller than 16 bytes may be more efficiently handled by the system as a struct.

<打击>这是 - 如果你需要按引用传递这使它成为一个类,无论大小

在第二个想法,你仍然可以通过结构由简单地引用在函数参数列表中指定裁判。

On the second thought, you can still pass struct by reference simply by specifying ref in the function parameter list.

所以,大的结构实际上是确定的,如果你通过引用传递,并作为类成员使用。

So, a large struct can actually be ok if you pass it by reference and use as a class member.

这篇关于有结构体&QUOT;快&QUOT;不是类 - 总体上还是在.NET框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆