Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does having a dynamic variable affect performance?
    primarykey
    data
    text
    <p>I have a question about the performance of dynamic in C#. I've read dynamic makes the compiler run again, but what does it do? </p> <p>Does it have to recompile the whole method with the dynamic variable used as a parameter or just those lines with dynamic behavior/context? </p> <p>I've noticed that using dynamic variables can slow down a simple for loop by 2 orders of magnitude.</p> <p>Code I have played with:</p> <pre><code>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 (int i = 0; i &lt; ITERATIONS; i++) { sum += i; } stopwatch.Stop(); Console.WriteLine(string.Format("Elapsed {0}", stopwatch.ElapsedMilliseconds)); } private static void SumInt(Stopwatch stopwatch) { var sum = new Sum(); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i &lt; ITERATIONS; i++) { sum.intSum += i; } stopwatch.Stop(); Console.WriteLine(string.Format("Class Sum int Elapsed {0}", stopwatch.ElapsedMilliseconds)); } private static void SumInt(Stopwatch stopwatch, dynamic param) { var sum = new Sum2(); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i &lt; ITERATIONS; i++) { sum.intSum += i; } stopwatch.Stop(); Console.WriteLine(string.Format("Class Sum int Elapsed {0} {1}", stopwatch.ElapsedMilliseconds, param.GetType())); } private static void DynamicSum(Stopwatch stopwatch) { var sum = new Sum(); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i &lt; ITERATIONS; i++) { sum.DynSum += i; } stopwatch.Stop(); Console.WriteLine(String.Format("Dynamic Sum Elapsed {0}", stopwatch.ElapsedMilliseconds)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload