Skip to content

Commit

Permalink
perf: use fast setter for preload util
Browse files Browse the repository at this point in the history
  • Loading branch information
Clazex committed Mar 1, 2023
1 parent 38d0d9a commit 8ed4c0d
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions Osmi/Game/PreloadUtil.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
namespace Osmi.Game;

public static class PreloadUtil {
private static readonly LazyMap<Type, (FieldInfo fi, string sceneName, string path)[]> fields = new(t => t
.GetRuntimeFields()
private static readonly LazyMap<Type, (string sceneName, string path, Action<GameObject> setter)[]> entries = new(t => t
.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Filter(fi => {
if (!Attribute.IsDefined(fi, typeof(PreloadAttribute))) {
return false;
}

if (!fi.IsStatic) {
Logger.LogError(
$"[PreloadUtil] Preload field {fi.Name} on type {t.FullName} is not static"
);
return false;
}

if (fi.IsLiteral) {
Logger.LogError(
$"[PreloadUtil] Preload field {fi.Name} on type {t.FullName} is const"
Expand All @@ -33,12 +26,12 @@ public static class PreloadUtil {
})
.Map(fi => {
PreloadAttribute attr = fi.GetCustomAttribute<PreloadAttribute>();
return (fi, attr.SceneName, attr.Path);
return (attr.SceneName, attr.Path, fi.GetFastStaticSetter<GameObject>());
})
.ToArray()
);

public static List<(string, string)> GetPreloadNames<T>() => fields[typeof(T)]
public static List<(string, string)> GetPreloadNames<T>() => entries[typeof(T)]
.Map(tuple => (tuple.sceneName, tuple.path))
.ToList();

Expand All @@ -47,12 +40,12 @@ public static void SavePreloads<T>(Dictionary<string, Dictionary<string, GameObj
return;
}

fields[typeof(T)].ForEach(
tuple => tuple.fi.SetValue(null, preloadedObjects[tuple.sceneName][tuple.path])
entries[typeof(T)].ForEach(
tuple => tuple.setter.Invoke(preloadedObjects[tuple.sceneName][tuple.path])
);

fields.Remove(typeof(T));
entries.Remove(typeof(T));
}

static PreloadUtil() => OsmiHooks.GameInitializedHook += fields.Clear;
static PreloadUtil() => OsmiHooks.GameInitializedHook += entries.Clear;
}

0 comments on commit 8ed4c0d

Please sign in to comment.