fork download
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. namespace ConsoleApplication161
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. const int N = 100, M = 10000;
  11. var a = new Foo {A = 10, B = 10};
  12.  
  13. unchecked
  14. {
  15. int trash = 0;
  16. Stopwatch sw1 = new Stopwatch(), sw2 = new Stopwatch();
  17. for (int i = 0; i < N; i++)
  18. {
  19. if (i % 2 == 0)
  20. {
  21. for (int j = 0; j < M; j++)
  22. {
  23. sw1.Start();
  24. a.A = j;
  25. sw1.Stop();
  26.  
  27. sw2.Start();
  28. a.B = j;
  29. sw2.Stop();
  30.  
  31. trash += a.A + a.B;
  32. }
  33. }
  34. else
  35. {
  36. for (int j = 0; j < M; j++)
  37. {
  38. sw2.Start();
  39. a.B = j;
  40. sw2.Stop();
  41.  
  42. sw1.Start();
  43. a.A = j;
  44. sw1.Stop();
  45.  
  46. trash += a.A + a.B;
  47. }
  48.  
  49. }
  50. }
  51. Console.WriteLine(trash);
  52. Console.WriteLine("Время доступа к свойству = {0}", sw1.Elapsed);
  53. Console.WriteLine("Время доступа к полю = {0}", sw2.Elapsed);
  54. Console.WriteLine("Разница между ними составляет {0:P} в пользу {1}", Math.Abs(1 - sw1.ElapsedTicks / (double)sw2.ElapsedTicks), sw1.Elapsed < sw2.Elapsed ? "Свойства" : "Поля");
  55. }
  56. }
  57. }
  58.  
  59. class Foo
  60. {
  61. public int A { get; set; }
  62. public int B;
  63. }
  64. }
Success #stdin #stdout 1.04s 24248KB
stdin
Standard input is empty
stdout
1409065408
Время доступа к свойству = 00:00:00.2486812
Время доступа к полю = 00:00:00.2493950
Разница между ними составляет 0.29 % в пользу Свойства