Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using System.Linq.Expressions;
- using System.Collections.Generic;
- public static class FastActivator{
- private static bool Initialized = false;
- private static bool _isCreatingCache = false;
- private static Dictionary<Type, Func<object>> Cache;
- public static void CreateCache()
- {
- if (Initialized)
- return;
- Cache = new Dictionary<Type, Func<object>>();
- _isCreatingCache = true;
- var thr = new Thread(()=>
- {
- var time = System.DateTime.Now;
- UnityEngine.Debug.Log("Creating cache");
- foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
- {
- foreach(var t in asm.GetTypes())
- {
- if (t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters)
- {
- Cache[t] = Expression.Lambda<Func<object>>(Expression.New(t)).Compile();
- }
- }
- }
- _isCreatingCache = false;
- Initialized = true;
- UnityEngine.Debug.Log("Cache created in " + (DateTime.Now - time).TotalSeconds + " seconds");
- });
- thr.Start();
- }
- public static object CreateInstance(Type t)
- {
- if (!Initialized)
- {
- if (!_isCreatingCache)
- CreateCache();
- }
- if (!Cache.ContainsKey(t))
- {
- var shouldUnInit = (t.GetConstructor(Type.EmptyTypes) == null);
- if (shouldUnInit)
- {
- return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
- }
- else
- {
- return Activator.CreateInstance(t);
- }
- }
- return Cache[t]();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment