[C #] exercise caution when using DynamicInvoke

Source: Internet
Author: User

The Delegate class provides a variable parameter interface DynamicInvoke (params object [] args), which can be called through reflection when the specific types of delegation are unknown. It is very convenient, but the performance is greatly affected due to variable parameters and reflection. Design experiment: Define a delegate (the content of the delegate instance function is blank. This experiment only tests the call overhead, so the function body is removed to avoid extra interference ), this delegate is called 8x1024x1024 times in different ways. Solution 1: directly call the Delegate solution when the Delegate type is specified. 2. Use a Delegate variable to undertake the Delegate instance in advance, then, use the DynamicInvoke method of Delegate to call the Delegate solution 3 -- Obtain the MethodInfo to be called from the Delegate in advance, and then call the Delegate result through the Invoke method of MethodInfo: solution 1 is about 70 ms, solution 2 is about 8500 ms, and solution 3 is about ms. Obviously, when the delegate type is determined, only the overhead of callback function calling is required, the DynamicInvoke reflection call Delegate of the Delegate class has too much extra overhead. Obtaining the Delegate's MethodInfo in advance can reduce the overhead of DynamicInvoke's method searching, however, it is still unable to compare with the delegate call efficiency when determining the type. In solution 3, a parameter is converted to the object [] array before the Invoke method of MethodInfo is called. Because the Invoke method only accepts the object [] parameter, if you save this step, the consumption of solution 3 can be reduced to about MS, which is improved, but not much. Therefore, when determining the Delegate type, do not use the Delegate DynamicInvoke instead of the normal Delegate call.

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.