Re: Array.Sort a struct
- From: "James Park" <someone@xxxxxxxxxxx>
- Date: Sat, 4 Feb 2006 10:14:25 -0800
"Bill Butler" <qwerty@xxxxxxxx> wrote in message
news:oo5Ff.693$Zy3.477@xxxxxxxxxxx
Many people come the C# with a C++ mindset and choose structs over classes
for the wrong reasons.
They will ,by default, choose a struct over a class for a Plain Old
Data(POD) type.
They do this because they think of a struct as a lightweight class ( ie
faster).
They figure that they don't need that object baggage (methods and stuff)
In short, they do it to improve performance.
More often than not they actually get worse performance due to boxing and
full copying on method calls.
Objects access in c# is quite fast and most Properties will get inlined by
the JITer, so POD types should ,by default, be classes.
So, when should you consider converting your class to a struct?
Suppose you have a small object (not expensive to copy) and you create
alot of them in tight looping situations (a Point comes to mind.) . The
potential performance improvement comes from faster creation of the struct
on the stack. This is offset against longer method call times (unless the
struct is tiny),and Boxing (although generics can help). So if you have
tiny , immutable objects that you create frequently and it is effecting
performance, you MIGHT get a performance boost by changing it to a class.
The important thing to note is that it is the cost of creation that you
are saving. So structs might help in short lifetime conditions. The choice
should NOT be made lightly.
In C# the object should always be the DEFAULT unit of data storage.
In most situations it will outperform structs.
In the specific case of Gerrit's Playlist.
The data MIGHT be immutable (at least it is in his quick sample)
The data is NOT created frequently (he creates 1 for each file in a
folder)
His struct is small but not Tiny (more expensive method calls).
So, He could use a stuct to represent his data and most likely only suffer
a small performance hit.
Of course that depends on the actual logic.
The real point is that he probably chose the struct over a class in order
to make it MORE performant.
It is doubtful that the end result will bear this out.
This is why we tend to steer developers away from structs.
Thanks for the good explanation Bill.
.
- References:
- Array.Sort a struct
- From: Gerrit
- Re: Array.Sort a struct
- From: Jon Skeet [C# MVP]
- Re: Array.Sort a struct
- From: James Park
- Re: Array.Sort a struct
- From: Bill Butler
- Re: Array.Sort a struct
- From: James Park
- Re: Array.Sort a struct
- From: Bill Butler
- Array.Sort a struct
- Prev by Date: RE: Choosing implementing class for interface in config
- Next by Date: RE: Choosing implementing class for interface in config
- Previous by thread: Re: Array.Sort a struct
- Next by thread: Re: Array.Sort a struct
- Index(es):
Relevant Pages
|