开发者

C#: Are struct members more performant?

开发者 https://www.devze.com 2022-12-13 11:45 出处:网络
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

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消