KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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? Does it have to recompile the whole method with the dynamic variable used as a parameter or just those lines with dynamic behavior/context? I've noticed that using dynamic variables can slow down a simple for loop by 2 orders of magnitude. Code I have played with: 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 < 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 < 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 < ITERATIONS; i++) {
Tags (comma-separated)
Save Edits
Cancel