views:

82

answers:

1

On a blog entry, Luca Bolognese ponders this idea about structs vs. classes as member fields:

The reason to use a struct is to not allocate an additional object on the stack. This allows this solution to be as 'performant' as simply having coded the fields on the class itself. Or at least I think so ...

How accurate is this?

First, doesn't he mean allocate an additional object on the heap?

And, wouldn't using structs marginally decrease allocation time (especially if the class members were lazy-loaded) at the expense of increasing the memory footprint?

Would you recommend this practice of structs over classes in certain situations?

+3  A: 

I think he did mean to write heap, he just wrote stack by mistake.

The question of structs or classes comes up quite often. Here's one example. I think it's best to follow this commonly given advice:


MSDN has the answer: Choosing Between Classes and Structures.

Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.

Do not define a structure unless the type has all of the following characteristics:

* It logically represents a single value, similar to primitive types (integer, double, and so on).
* It has an instance size smaller than 16 bytes.
* It is immutable.
* It will not have to be boxed frequently.


Are there times you shouldn't follow this advice? Maybe, but only after you've proved it by profiling.

Mark Byers
Thanks Mark - so, to extend on the last item in that list: if I need to use/pass a class's field often (thus unboxing it) the field should not be a struct, yes?
Jeff Meatball Yang