When do I use value types? When do I use reference types?

Source: Internet
Author: User

The CLR supports two types: reference type and value type

For reference types, you have to know:

  1. Memory must be allocated from the managed heap
  2. Each object allocated on the heap has some extra members that must be initialized
  3. Other bytes in the object are always set to zero
  4. Garbage collection may be enforced when an object is allocated from the managed heap

What you need to know about value types:

  1. Lightweight type
  2. Generally allocated on the thread stack (sometimes also embedded as a field in the object of the reference type)
  3. A value type instance variable does not contain a pointer to an instance, and the variable contains the field of the instance itself
  4. Instances of value types are not controlled by the garbage collector

Value types can sometimes provide better performance, specifically the type should not be declared as a value type unless all of the following conditions are met.

That is to say, consider declaring a type as a value type if all of the following conditions are true:

  • Type has the behavior of primitive types. That is, a very simple type, no member will modify any instance fields of the type
  • Types do not need to inherit from other types, nor do they derive any other type (because value types are implicitly sealed)

Another type of instance size is also under consideration,

Because the arguments are passed by default by value, the performance is affected by the replication of the fields in the value type instance.

A method that is also defined to return a value type when returned, the field in the instance is copied to the memory allocated by the caller, which affects performance.

Therefore, in order to declare a type as a value type, you must satisfy any of the above criteria:

  • Small instances of type
  • Type is large (but not passed as a method argument and not returned from the method), remember

When do I use value types? When do I use reference types?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.