Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

data structures - Are Structs "faster" than Classes - In general or in the .NET framework?

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;
}

and then, with reference to the following code:

TimmysStructOfGoodness someStructOfGoodness = new blah blah blah...

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

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.

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(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.

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

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.

This is - if you need to pass it by reference make it a class, regardless of the size.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...