Skip to content

Commit

Permalink
Use a more traditional method of caching
Browse files Browse the repository at this point in the history
  • Loading branch information
peppy committed Sep 8, 2021
1 parent 81c9d83 commit a622a0b
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions osu.Game/Configuration/SettingSourceAttribute.cs
Expand Up @@ -4,6 +4,7 @@
#nullable enable

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -167,7 +168,30 @@ public static IEnumerable<Drawable> CreateSettingsControls(this object obj)
}
}

public static IEnumerable<(SettingSourceAttribute, PropertyInfo)> GetSettingsSourceProperties<T>(this T obj) => SettingSourceCache<T>.SettingSourceProperties;
private static readonly ConcurrentDictionary<Type, IEnumerable<(SettingSourceAttribute, PropertyInfo)>> property_info_cache = new ConcurrentDictionary<Type, IEnumerable<(SettingSourceAttribute, PropertyInfo)>>();

public static IEnumerable<(SettingSourceAttribute, PropertyInfo)> GetSettingsSourceProperties(this object obj)
{
var type = obj.GetType();

if (!property_info_cache.TryGetValue(type, out var properties))
property_info_cache[type] = properties = getSettingsSourceProperties(type);

return properties;
}

private static IEnumerable<(SettingSourceAttribute, PropertyInfo)> getSettingsSourceProperties(Type type)
{
foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
{
var attr = property.GetCustomAttribute<SettingSourceAttribute>(true);

if (attr == null)
continue;

yield return (attr, property);
}
}

public static ICollection<(SettingSourceAttribute, PropertyInfo)> GetOrderedSettingsSourceProperties(this object obj)
=> obj.GetSettingsSourceProperties()
Expand All @@ -185,14 +209,5 @@ private class ModDropdownControl : DropdownControl
protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 100);
}
}

private static class SettingSourceCache<T>
{
public static (SettingSourceAttribute, PropertyInfo)[] SettingSourceProperties { get; } =
typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)
.Select(property => (property.GetCustomAttribute<SettingSourceAttribute>(), property))
.Where(pair => pair.Item1 != null)
.ToArray();
}
}
}

0 comments on commit a622a0b

Please sign in to comment.