Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...