Reading notes-CLR via C # Chapter 4-7

Source: Internet
Author: User
Tags emit shallow copy unique id

Objective

This book in the past few years fragmented read two or three times, as a classic book, should repeat read and reread, since I began to write Bo, I am also ready to think of the classic good book reread carefully read it again, and put the notes into the blog, good memory than bad writing, but also in the process can deepen their understanding of the depth, And, of course, sharing it with friends from the technology community.

Ancestor –object of the object
    • Public methods
      • Equals, virtual method, object equality, default call Runtimehelpers.equals method
      • GetHashCode, a virtual method that returns a hash (a randomly distributed integer) that is used as a key in a hash table
      • ToString, which returns this by default. GetType (). FullName, the debugger calls this method by default
      • GetType, returns an instance of an object derived from type, containing the type metadata information for the object, and used for reflection mates. Design as a non-virtual method prevents rewriting because overrides can cause the type of deception to break type safety
    • Protected methods
      • MemberwiseClone, non-virtual method, shallow copy (create new instance, copy instance field), feel is a chicken ribs!
      • Finalize, after the GC determines that the object is garbage, call this virtual method before the memory is actually reclaimed, and override this method if cleanup is required
The process of the new object
    • Count bytes (instance field + Extra member (type Object pointer + Synchronous Fast index))
    • Allocate memory for response bytes from the managed heap, all bytes set to 0
    • Initialize type object pointer and synchronization block index
    • Initialize all instance fields (0 or null)
    • Call the constructor (at the same time to call up the constructor of object)
    • Returns a reference to a heap
Procedure for method invocation
    • Calling a static method
      • CLR Anchor type Object
      • Find the record entry in the Type Object method table that corresponds to the method being called
      • JIT compilation (if required)
      • Execute the compiled native code
    • Calling a non-virtual instance method
      • CLR location emit call variable corresponding type Object method table
      • If found then locate
      • If you cannot find the address of a type object, follow the base class for backtracking
      • Navigate to the method, and then execute
    • Invoke the actual case method
      • JIT generates additional code for the compiler
      • Check for positional emit call variables
      • Object that is called by Address Locator (actual type)
      • Checking method table records for object type pointers
Construction of types and instances

When the CLR runs in a process, a special object is created for the System.Type type, and the type object of any class is an "instance" of that object, and their type object pointer member Initializes a reference to the type object. Type an object pointer to itself. GetType returns a pointer to the object's type object (an address) that can determine the object's true type

Type
    • Signed byte and unsigned numeric types are not CLS compliant, such as Sbyte,ushort,uint,ulong
    • Char is a 16-bit Unicode character, and decimal is a 128-bit high-precision floating-point value
    • Primitive numeric type conversions, implicit if secure (no data loss), or explicit conversions are required
    • Fractional to integer is always truncated
    • Operations inside decimal are overloaded
    • Checked symbol is invalid for decimal, decimal enforces security checks, unsafe throws an exception
    • BigInteger uses the UInt32 array internally to represent any large integer with no upper and lower bounds, never causing overflowexception, but if the value is too large, there is not enough memory to change the size of the array. Operations on BigInteger may throw outofmemoryexception exceptions
Reference type
    • Allocation operations: Managed heap allocation memory, additional members (type Object pointers and synchronous index blocks) class.
    • A garbage collection operation may be enforced when an object is allocated
    • Copy of reference type, copy only memory address
    • field layout defaults to use System.Runtime.InteropServices.StructLayoutAttribute.LayoutKind.Auto
    • int x = 4; Object o = x; Short y = (short) (int) O; Note that unpacking is the right type before you can transform it.
Value type
    • Lightweight type, no additional members, avoids frequent memory allocations to save performance
    • Typically allocated on the stack, no pointer reference is required
    • Not controlled by the garbage collector, so it also eases the pressure on the managed heap and GC
    • Enums derive from Enum, enum and other value types are derived from ValueType
    • The default implicit seal is not derived and can implement an interface
    • New value type, so the field initializes bit 0, if the new compiler does not think the field is not initialized
    • Value types do not fit too large (16 bytes or less) and are too large to increase the overhead of memory copies
    • ValueType overrides the Equals and GetHashCode methods, using all field calculations and matches by default
    • Value type suggestions are immutable and fields are marked as ReadOnly comparison specification
    • It is recommended to rewrite your own GetHashCode and equals methods to save performance and avoid boxing
    • Value type memory reclamation, not through the Finalize method
    • field layout defaults to use System.Runtime.InteropServices.StructLayoutAttribute.LayoutKind.Sequential
    • Using Layoutkind.auto can improve performance if unmanaged interactions are not considered
    • Value types do not have a synchronized block index, so you cannot use lock or monitor to allow multithreading to synchronize access to instances
    • A value type calling a base class virtual method can cause boxing, and transitioning to an interface causes boxing
Same Sex and equality
    • Identity Use ReferenceEquals
    • equals and = = usually represent equality, because it is a virtual method that is overridden
    • Use generic iequalable<t> to avoid packing and unpacking, and type-safe
    • It is recommended that equals and GetHashCode be implemented together to ensure equality algorithms and hashing algorithms are consistent
    • Hash algorithm rules:
      • Good random distribution, when the hash table gets the best performance
      • Try not to apply the GetHashCode of the base class
      • The algorithm should use at least one instance field, and this field is immutable
      • If you want to get the unique ID of the object reference, use RuntimeHelpers's GetHashCode
      • ValueType's GetHashCode uses reflection and XOR operations, which are poorly performing and recommend rewriting
      • Hash codes are not suitable for persistent identities and may result in a "hash collision"
Dynamic type
    • Application Scenarios
      • Interacting with dynamic languages, such as Python or ruby
      • Communication with COM objects that support the IDispatch interface
      • Communicate with the DOM of HTML
    • Ignoring compilation checks, the compiler generates a special IL
    • Payload, payload, using runtime Binder runtime binders
    • Payload runtime generates dynamic code, enters the memory-resident assembly, anonymously hosts the Dynamicmethods assembly
    • The compiler allows dynamic and other types to be transformed using implicit transformation syntax (boxing unboxing and exceptions can occur)
    • Allows the use of implicit types to replicate dynamic types, and type inference
    • If the call to a method that returns a value of dynamic returns void, it is actually worth the null
    • Specific scenarios where the compiler transforms dynamic into specific interfaces (such as IEnumerable and IDisposable)
    • The runtime judges the transformation results, and if the transformation fails, Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
    • Dynamic can simplify reflection and invocation, but with extra overhead, use caution
    • Other components dynamically call Idynamicobjectprovider–> Getmetaobject () –> dynamicmetaobject derived types
    • If not implemented, it is treated as a C # object, which is reflected at run time
Type and member base
  • Friend Assembly
      • [Assembly:internalvisibleto ("AssemblyName, publickey= ...")]
      • Note: Version and language culture not included
  • The accessibility of interface members is public, and it is forbidden to explicitly specify
  • Derived classes can relax accessibility and do not allow tightening
  • Static class
      • The default abstract sealed, which inherits only object, does not allow interfaces to be implemented
  • Method invocation
      • Call directives, static methods (specified types), instance methods (specifying object variables), and virtual methods. Call directives are often used to invoke a virtual method in a non-virtual way
      • The callvirt directive, which invokes an instance method and a virtual method, but cannot invoke a static method. The call emits the actual type of the calling object and is then called in a polymorphic manner. Because the null condition is checked, it is slightly slower than the call instruction. Even if you call a non-virtual instance method, you also perform a null check, using callvirt to invoke a non-virtual method in order to perform a null check. C # calls all instance methods using Callvirt, calling base classes such as base. ToString () enforces the use of non-virtual call directives. Infinite recursion to stack overflow if virtual method is called
      • Because the value type is not null and there are no polymorphic calls, the compiler generally calls the method of the value type in a non-virtual way
      • Recommended to avoid virtual methods, 1: Low performance 2: Non-embedding (inline) 3: weakening version control
  • Constant
      • Using primitive type definitions
      • Implicitly is a static member instead of an instance member
      • Defining a constant value creates metadata, a constant value embedded in IL, and does not run when memory is created
      • Constants do not run when you dynamically reference an assembly lookup value, and if you want to reference a lookup, use readonly
  • Volatile indicates that the compiler CLR or hardware does not perform some "thread-insecure" optimizations
  • Field
      • Type field (static) and instance field (non-static)
      • Type fields, which are assigned in the type object, are created when the type is loaded into the AppDomain (when any method referencing that type is first JIT-compiled)
      • The corresponding instance field, the dynamic memory that holds the field data, is allocated when an instance of the type is constructed
      • Note: You can use reflection to modify the ReadOnly field
  • Method
      • Inline initialization of a field in a class is actually done in the constructor
      • Inline syntax needs to consider performance issues
      • If the class is abstract, the accessibility of the default constructor is protected

Reading notes-CLR via C # Chapter 4-7

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.