shadowndacorner

c# fast generic initializer

Aug 9th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Linq.Expressions;
  4. using System.Collections.Generic;
  5.  
  6. public static class FastActivator{
  7.     private static bool Initialized = false;
  8.     private static bool _isCreatingCache = false;
  9.     private static Dictionary<Type, Func<object>> Cache;
  10.  
  11.     public static void CreateCache()
  12.     {
  13.         if (Initialized)
  14.             return;
  15.  
  16.         Cache = new Dictionary<Type, Func<object>>();
  17.         _isCreatingCache = true;
  18.         var thr = new Thread(()=>
  19.         {
  20.             var time = System.DateTime.Now;
  21.             UnityEngine.Debug.Log("Creating cache");
  22.             foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
  23.             {
  24.                 foreach(var t in asm.GetTypes())
  25.                 {
  26.                     if (t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
  27.                     {
  28.                         Cache[t] = Expression.Lambda<Func<object>>(Expression.New(t)).Compile();
  29.                     }
  30.                 }
  31.             }
  32.             _isCreatingCache = false;
  33.             Initialized = true;
  34.             UnityEngine.Debug.Log("Cache created in " + (DateTime.Now - time).TotalSeconds + " seconds");
  35.         });
  36.         thr.Start();
  37.     }
  38.  
  39.     public static object CreateInstance(Type t)
  40.     {
  41.         if (!Initialized)
  42.         {
  43.             if (!_isCreatingCache)
  44.                 CreateCache();
  45.         }
  46.  
  47.         if (!Cache.ContainsKey(t))
  48.         {
  49.             var shouldUnInit = (t.GetConstructor(Type.EmptyTypes) == null);
  50.             if (shouldUnInit)
  51.             {
  52.                 return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
  53.             }
  54.             else
  55.             {
  56.                 return Activator.CreateInstance(t);
  57.             }
  58.         }
  59.         return Cache[t]();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment