C# Dynamic Keyword — Run-time penalty?

后端 未结 6 1219
春和景丽
春和景丽 2020-12-01 14:20

Does defining an instance as dynamic in C# mean:

  1. The compiler does not perform compile-time type checking, but run-time checking takes place like it always

6条回答
  •  感情败类
    2020-12-01 15:04

    I made a simple test: 100000000 assignments to a variable as a dynamic vs. the same number of direct double assignments, something like

    int numberOfIterations = 100000000;
    
    Stopwatch sw = new Stopwatch();
    sw.Start();
    
    for (int i = 0; i < numberOfIterations; i++)
    {
        var x = (dynamic)2.87; 
    }
    
    sw.Stop();
    sw.Restart();
    
    for (int i = 0; i < numberOfIterations; i++)
    {
        double y = 2.87; 
    }
    sw.Stop();
    

    In the first loop (with dynamic) it took some 500ms; in the second one about 200ms. Certainly, the performance loss depends of what you do in your loops, these representing a simplest action possible.

提交回复
热议问题