C # uses binding handles to reduce memory consumption of processes

Source: Internet
Author: User
Tags mscorlib


In many applications, a set of types (type) or type members (derived from MemberInfo) are bound, and these objects are saved in a collection of some form. Later, the collection is searched, a specific object is found, and the object is called. This is a good mechanism, but there is a small problem: the type and MemberInfo derived objects require a lot of memory. If an application accommodates too many of these classes, but only occasionally uses them, the memory of the application grows dramatically, impacting the performance of the application.

Internally, the CLR represents this information in a more streamlined form. The CLR creates these objects for applications just to simplify the work of developers. The CLR does not need these large objects at run time. If you need to cache a large number of type and MemberInfo derived objects, developers can use run-time handles (runtime handle) instead of objects, thereby reducing the working set (memory consumed). The FCL defines 3 run-time handle types (both in the System namespace), Runtimetypehandle,runtimefieldhandle,rumtimemethodhandle. All three types are value types, and they contain only one field, which is a IntPtr, so that these types of instances are quite memory-saving. The Itptr field is a handle that references a type, field, or method in the loader heap of the AppDomain. Conversion method:

    • Type→runtimetypehandle, by querying the type's read-only field property Typehandle.

    • Runtimetypehandle→type, Gettypefromhanlde by calling the static method of Type.

    • Fieldinfo→runtimefieldhandle, read-only field fieldhandle by querying the FieldInfo instance.

    • Runtimefieldhandle→fieldinfo, by calling the FieldInfo static method GetFieldFromHandle.

    • Methodinfo→runtimemethodhandle, read-only field methodhandle by querying the methodinof instance.

    • Runtimemethodhandle→methodinfo, by calling the MethodInfo static method Getmethodfromhandle.

The following example gets a number of MethodInfo objects, translates them into runtimemethodhandle instances, and demonstrates the memory differences before and after the conversion.

 private void Useruntimehandletoreducememory () {Show ("before doing anything");//Build me from all methods in MSCorlib.dll                        Thodinfos Object Cache list<methodbase> Methodinfos = new list<methodbase> (); foreach (Type T in typeof (object).                Assembly.getexportedtypes ()) {if (t.isgenerictype) continue;                methodbase[] mbs = T.getmethods (C_BF);            Methodinfos.addrange (MBS);            }//shows the number of methods and the size of the heap after binding all methods Console.WriteLine ("# of methods={0:###,###}", Methodinfos.count); Show ("After building cache of MethodInfo objects");//build RuntimeMethodHandle cache for all MethodInfo objects List<runtim            emethodhandle> methodhandles = new list<runtimemethodhandle> ();            Methodhandles = methodinfos.convertall<runtimemethodhandle> (M = m.methodhandle);            Show ("Holding MethodInfo and RuntimeMethodHandle"); Gc. KeepAlive (methodhandles);//prevent cache from being prematurely garbage collected            Methodinfos = null;//now allows cache garbage collection Show ("After freeing MethodInfo objects");            Methodinfos = methodhandles.convertall<methodbase> (r = Methodbase.getmethodfromhandle (r));            Show ("Size of heap after re-creating MethodInfo objects"); Gc. KeepAlive (methodhandles);//prevents cache from being prematurely garbage collected by GC. KeepAlive (Methodinfos);//prevent cache from being prematurely garbage collected Methodinfos = null;//now allow cache garbage collection Methodhandles = null;//now allows cache garbage        Recycle Show ("After freeing MethodInfo and Methodhandle objects"); }

The results are as follows:

Heap Size =     114,788-before doing anything# of methods=10,003heap Size =   2,205,652-after Building cache of Meth Odinfo objectsheap size =   2,245,744-holding MethodInfo and runtimemethodhandleheap size =   2,171,976-after free  ing MethodInfo objectsheap size =   2,327,516-size of heap after re-creating MethodInfo objectsheap Size =     247,028 -After freeing MethodInfo and Methodhandle objects

This article is organized from the NET CLR via C #

Author: jiankunking Source: http://www.php.cn/

In many applications, a set of types (type) or type members (derived from MemberInfo) are bound, and these objects are saved in a collection of some form. Later, the collection is searched, a specific object is found, and the object is called. This is a good mechanism, but there is a small problem: the type and MemberInfo derived objects require a lot of memory. If an application accommodates too many of these classes, but only occasionally uses them, the memory of the application grows dramatically, impacting the performance of the application.

Internally, the CLR represents this information in a more streamlined form. The CLR creates these objects for applications just to simplify the work of developers. The CLR does not need these large objects at run time. If you need to cache a large number of type and MemberInfo derived objects, developers can use run-time handles (runtime handle) instead of objects, thereby reducing the working set (memory consumed). The FCL defines 3 run-time handle types (both in the System namespace), Runtimetypehandle,runtimefieldhandle,rumtimemethodhandle. All three types are value types, and they contain only one field, which is a IntPtr, so that these types of instances are quite memory-saving. The Itptr field is a handle that references a type, field, or method in the loader heap of the AppDomain. Conversion method:

    • Type→runtimetypehandle, by querying the type's read-only field property Typehandle.

    • Runtimetypehandle→type, Gettypefromhanlde by calling the static method of Type.

    • Fieldinfo→runtimefieldhandle, read-only field fieldhandle by querying the FieldInfo instance.

    • Runtimefieldhandle→fieldinfo, by calling the FieldInfo static method GetFieldFromHandle.

    • Methodinfo→runtimemethodhandle, read-only field methodhandle by querying the methodinof instance.

    • Runtimemethodhandle→methodinfo, by calling the MethodInfo static method Getmethodfromhandle.

The following example gets a number of MethodInfo objects, translates them into runtimemethodhandle instances, and demonstrates the memory differences before and after the conversion.

 private void Useruntimehandletoreducememory () {Show ("before doing anything");//Build me from all methods in MSCorlib.dll                        Thodinfos Object Cache list<methodbase> Methodinfos = new list<methodbase> (); foreach (Type T in typeof (object).                Assembly.getexportedtypes ()) {if (t.isgenerictype) continue;                methodbase[] mbs = T.getmethods (C_BF);            Methodinfos.addrange (MBS);            }//shows the number of methods and the size of the heap after binding all methods Console.WriteLine ("# of methods={0:###,###}", Methodinfos.count); Show ("After building cache of MethodInfo objects");//build RuntimeMethodHandle cache for all MethodInfo objects List<runtim            emethodhandle> methodhandles = new list<runtimemethodhandle> ();            Methodhandles = methodinfos.convertall<runtimemethodhandle> (M = m.methodhandle);            Show ("Holding MethodInfo and RuntimeMethodHandle"); Gc. KeepAlive (methodhandles);//prevent cache from being prematurely garbage collected            Methodinfos = null;//now allows cache garbage collection Show ("After freeing MethodInfo objects");            Methodinfos = methodhandles.convertall<methodbase> (r = Methodbase.getmethodfromhandle (r));            Show ("Size of heap after re-creating MethodInfo objects"); Gc. KeepAlive (methodhandles);//prevents cache from being prematurely garbage collected by GC. KeepAlive (Methodinfos);//prevent cache from being prematurely garbage collected Methodinfos = null;//now allow cache garbage collection Methodhandles = null;//now allows cache garbage        Recycle Show ("After freeing MethodInfo and Methodhandle objects"); }

The results are as follows:

Heap Size =     114,788-before doing anything# of methods=10,003heap Size =   2,205,652-after Building cache of Meth Odinfo objectsheap size =   2,245,744-holding MethodInfo and runtimemethodhandleheap size =   2,171,976-after free  ing MethodInfo objectsheap size =   2,327,516-size of heap after re-creating MethodInfo objectsheap Size =     247,028 -After freeing MethodInfo and Methodhandle objects

The above is that C # uses binding handles to reduce the memory consumption of the process, and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.