Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EntityDescriptorsWarmup.cs 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Svelto.ECS.Internal;
  5. namespace Svelto.ECS
  6. {
  7. public static class EntityDescriptorsWarmup
  8. {
  9. /// <summary>
  10. /// c# Static constructors are guaranteed to be thread safe
  11. /// Warmup all EntityDescriptors and ComponentTypeID classes to avoid huge overheads when they are first used
  12. /// </summary>
  13. internal static void Init()
  14. {
  15. List<Assembly> assemblies = AssemblyUtility.GetCompatibleAssemblies();
  16. foreach (Assembly assembly in assemblies)
  17. {
  18. var typeOfEntityDescriptors = typeof(IEntityDescriptor);
  19. foreach (Type type in AssemblyUtility.GetTypesSafe(assembly))
  20. {
  21. if (type.IsInterface == false && typeOfEntityDescriptors.IsAssignableFrom(type)) //IsClass and IsSealed and IsAbstract means only static classes
  22. {
  23. try
  24. {
  25. //the main goal of this iteration is to warm up the component builders and descriptors
  26. //note: I could have just instanced the entity descriptor, but in this way I will warm up the EntityDescriptorTemplate too
  27. var warmup = typeof(EntityDescriptorTemplate<>).MakeGenericType(type);
  28. System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(warmup.TypeHandle);
  29. }
  30. catch (Exception e)
  31. {
  32. continue;
  33. }
  34. }
  35. }
  36. var typeOfComponents = typeof(_IInternalEntityComponent);
  37. //the main goal of this iteration is to warm up the component IDs
  38. foreach (Type type in AssemblyUtility.GetTypesSafe(assembly))
  39. {
  40. if (type.IsInterface == false && typeOfComponents.IsAssignableFrom(type)) //IsClass and IsSealed and IsAbstract means only static classes
  41. {
  42. try
  43. {
  44. var componentType = typeof(ComponentTypeID<>).MakeGenericType(type);
  45. //is called only once ever, even if runs multiple times.
  46. //this warms up the component builder. There could be different implementation of components builders for the same component type in theory
  47. System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(componentType.TypeHandle);
  48. }
  49. catch (Exception e)
  50. {
  51. continue;
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }