Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[perf] Cache Runtime.IsUserType results #15149

Merged
merged 4 commits into from
Jun 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions src/ObjCRuntime/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public partial class Runtime {
static List <object> delegates;
static List <Assembly> assemblies;
static Dictionary <IntPtr, GCHandle> object_map;
static Dictionary <IntPtr, bool> usertype_cache;
static object lock_obj;
static IntPtr NSObjectClass;
static bool initialized;
Expand Down Expand Up @@ -272,6 +273,7 @@ unsafe static void Initialize (InitializationOptions* options)
Runtime.options = options;
delegates = new List<object> ();
object_map = new Dictionary <IntPtr, GCHandle> (IntPtrEqualityComparer);
usertype_cache = new Dictionary <IntPtr, bool> (IntPtrEqualityComparer);
intptr_ctor_cache = new Dictionary<Type, ConstructorInfo> (TypeEqualityComparer);
intptr_bool_ctor_cache = new Dictionary<Type, ConstructorInfo> (TypeEqualityComparer);
lock_obj = new object ();
Expand Down Expand Up @@ -1735,11 +1737,31 @@ internal static IntPtr GetProtocolForType (Type type)
throw new ArgumentException ($"'{type.FullName}' is an unknown protocol");
}

[BindingImpl (BindingImplOptions.Optimizable)]
internal static bool IsUserType (IntPtr self)
{
var cls = Class.object_getClass (self);
lock (usertype_cache) {
#if NET
ref var result = ref CollectionsMarshal.GetValueRefOrAddDefault (usertype_cache, cls, out var exists);
if (!exists)
result = SlowIsUserType (cls);
#else
if (!usertype_cache.TryGetValue (cls, out var result)) {
result = SlowIsUserType (cls);
usertype_cache.Add (cls, result);
}
#endif
return result;
}
}

#if __MACOS__
static IntPtr selSetGCHandle = Selector.GetHandle ("xamarinSetGCHandle:flags:");
#endif

[BindingImpl (BindingImplOptions.Optimizable)]
static bool SlowIsUserType (IntPtr cls)
{
unsafe {
if (options->RegistrationMap is not null && options->RegistrationMap->map_count > 0) {
var map = options->RegistrationMap->map;
Expand All @@ -1752,8 +1774,11 @@ internal static bool IsUserType (IntPtr self)
return false;
}
}

#if __MACOS__
return Class.class_getInstanceMethod (cls, selSetGCHandle) != IntPtr.Zero;
#else
return Class.class_getInstanceMethod (cls, Selector.GetHandle ("xamarinSetGCHandle:flags:")) != IntPtr.Zero;
#endif
}

static unsafe int FindUserTypeIndex (MTClassMap* map, int lo, int hi, IntPtr cls)
Expand Down