More dynamic calling code

xiaoxiao2021-03-06  61

Last time I saw a comparison of dynamically calling code, the example used in the MSDN website appeared to be more complicated. To calculate a complex multi-item child, partially cut it, dynamically form code segment to be circulated. Detailed view. Several dynamic generating code patterns in .NET comparison. Today, I saw another comparative article written by Microsoft C # team, in order to illustrate the performance and calculation accuracy, reduce the impact of compilation and optimization due to complex function, he uses an extremely simple Example: Enter a parameter, then return this parameter to add one, such a simple function, optimization, and unopened code should not have a difference.

public

Class

PROCESSOR

{Public int process (int value) {returnavalue 1;}}

In contrast, in addition to the last few, it also added a proxy mode call to compare. Direct call

int

Value

=

Processor.Process (i);

2. Type.invokemember () calls with reflective mechanisms.

Type T

=

Typeof

(Processor);

int

Value

=

(

int

) T.Invokemember

"

PROCESS

"

BindingFlags.instance

|

Bindingflags.public

|

BindingFlags.InvokeMethod,

NULL

, Processor,

New

Object

[]

{i}

);

3. Through an interface

public

Interface

IProcessor

{INT Process (int value);

4. Through a commissioned delegate

public

Delegate

int

ProcessCaller

int

Value; ProcessCaller ProcessCaller

=

New

ProcessCaller (Processor.Process);

int

Value

=

ProcessCaller (i);

5. Establish a commissioned re-dynamic call by reflex mechanism

Type delegateType

=

CreateCustomDelegate (MethodInfo); DELEGATE P

=

Delegate.createDelegate (delegateType, Process,

"

PROCESS

"

);

int

Value

=

(

int

P. DynamicInvoke

New

Object

[]

{i}

);

6. Milled mode

For 2 and 5, due to the use of reflective mechanisms, it is not possible to establish an intermediate temporary object to deliver parameters, and the parameters and return values, etc., therefore spend a lot of machine time.

Below is a result of the run (100,000 times in loop):

in conclusion:

1. Direct calls are the fastest.

2. The interface call is fast programming, and the meta-programming is faster than the entrustment method, but Microsoft believes whidbey will greatly optimize the principal-calling mode, so that it approaches the level of interface calls.

3. Directly use Type's reflex mechanism is the slowest speed, and it is slow to dynamically call to the reflex mechanism.

4. Direct use delegate is not flexible, sometimes it needs to be invoked with reflex mechanisms, but will reduce performance. It is desirable that WHIDBey can improve the performance of the entrusted performance, and flexibility is to sacrifice performance. Code

转载请注明原文地址:https://www.9cbs.com/read-117247.html

New Post(0)