SHARE
TWEET

Struct vs Class with GC overhead

a guest Aug 23rd, 2012 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. struct MyStruct
  5. {
  6.     public int Id;
  7.     public string Name;
  8.     public DateTime DateOfBirth;
  9.     public string Comment;
  10. }
  11. class MyClass
  12. {
  13.     public int Id { get; set; }
  14.     public string Name { get; set; }
  15.     public DateTime DateOfBirth { get; set; }
  16.     public string Comment { get; set; }
  17. }
  18. static class Program
  19. {
  20.     static void Main()
  21.     {
  22.         var dob = DateTime.Today;
  23.  
  24.         const int SIZE = 1 * 1000 * 1000;
  25.         const int REPEATS = 100 * 1000 * 1000;
  26.  
  27.         Stopwatch watch = Stopwatch.StartNew();
  28.         var s = new MyStruct[SIZE];
  29.         for (int i = 0; i < REPEATS; i++)
  30.         {
  31.             s[i % SIZE] = new MyStruct
  32.             {
  33.                 Comment = "abc", DateOfBirth = dob,
  34.                 Id = 123, Name = "def"
  35.             };
  36.         }
  37.         watch.Stop();
  38.         Console.WriteLine("struct/field: "
  39.                   + watch.ElapsedMilliseconds + "ms");
  40.  
  41.         watch = Stopwatch.StartNew();
  42.         var c = new MyClass[SIZE];
  43.         for (int i = 0; i < REPEATS; i++)
  44.         {
  45.             c[i % SIZE] = new MyClass
  46.             {
  47.                 Comment = "abc", DateOfBirth = dob,
  48.                 Id = 123, Name = "def"
  49.             };
  50.         }
  51.         watch.Stop();
  52.         Console.WriteLine("class/property: "
  53.                    + watch.ElapsedMilliseconds + "ms");
  54.         Console.ReadLine();
  55.     }
  56. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top