相关疑难解决方法(0)

动态变量如何影响性能?

我对dynamicC#的性能有疑问.我读过dynamic让编译器再次运行,但是它做了什么?

是否必须dynamic使用用作参数的变量或仅具有动态行为/上下文的行重新编译整个方法?

我注意到使用dynamic变量可以将简单的for循环减慢2个数量级.

我玩过的代码:

internal class Sum2
{
    public int intSum;
}

internal class Sum
{
    public dynamic DynSum;
    public int intSum;
}

class Program
{
    private const int ITERATIONS = 1000000;

    static void Main(string[] args)
    {
        var stopwatch = new Stopwatch();
        dynamic param = new Object();
        DynamicSum(stopwatch);
        SumInt(stopwatch);
        SumInt(stopwatch, param);
        Sum(stopwatch);

        DynamicSum(stopwatch);
        SumInt(stopwatch);
        SumInt(stopwatch, param);
        Sum(stopwatch);

        Console.ReadKey();
    }

    private static void Sum(Stopwatch stopwatch)
    {
        var sum = 0;
        stopwatch.Reset();
        stopwatch.Start();
        for …
Run Code Online (Sandbox Code Playgroud)

c# performance dynamic

119
推荐指数
2
解决办法
4万
查看次数

如何基于C#<4中的参数运行时类型调度方法?

我有一个对象o,其保证在运行时是三种类型之一A,B或者C,所有这些实现公共接口的I.我可以控制I,但不能A,BC.(因此我可以使用空标记接口,或者通过使用接口以某种方式利用类型中的相似性,但我无法添加新方法或更改类型中的现有方法.)

我也有一系列的方法MethodA,MethodBMethodC.o查找运行时类型,然后将其用作这些方法的参数.

public void MethodA(A a) { ... }
public void MethodB(B b) { ... }
public void MethodC(C c) { ... }
Run Code Online (Sandbox Code Playgroud)

使用此策略,现在必须对类型执行检查o以确定应调用哪个方法.相反,我想简单地有三个重载方法:

public void Method(A a) { ... } // these are all overloads of each other
public void Method(B b) { ... }
public void Method(C c) { ... …
Run Code Online (Sandbox Code Playgroud)

c# methods dispatch

5
推荐指数
2
解决办法
807
查看次数

标签 统计

c# ×2

dispatch ×1

dynamic ×1

methods ×1

performance ×1