Skip to content

Commit 05f57b3

Browse files
[CoreCLR] Cache JNI to Managed type mappings (#10170)
I noticed there were *thousands* of log messages such as: I monodroid: Loaded type: Java.Lang.Object printed in logcat while running unit tests. It turns out we aren't caching the resolved type mappings when the `GetJavaToManagedType` method is called from `AndroidRuntime.GetTypesForSimpleReference`. This hurts performance because the call to `clr_typemap_java_to_managed` is fairly expensive. This change makes sure we're using the `TypeManagerMapDictionaries.JniToManaged` cache in this codepath.
1 parent 3c63049 commit 05f57b3

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/Mono.Android/Java.Interop/TypeManager.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -253,14 +253,27 @@ static Type monovm_typemap_java_to_managed (string java_type_name)
253253

254254
internal static Type? GetJavaToManagedType (string class_name)
255255
{
256-
Type? type = JNIEnvInit.RuntimeType switch {
256+
lock (TypeManagerMapDictionaries.AccessLock) {
257+
return GetJavaToManagedTypeCore (class_name);
258+
}
259+
}
260+
261+
static Type? GetJavaToManagedTypeCore (string class_name)
262+
{
263+
if (TypeManagerMapDictionaries.JniToManaged.TryGetValue (class_name, out Type? type)) {
264+
return type;
265+
}
266+
267+
type = JNIEnvInit.RuntimeType switch {
257268
DotNetRuntimeType.MonoVM => monovm_typemap_java_to_managed (class_name),
258269
DotNetRuntimeType.CoreCLR => clr_typemap_java_to_managed (class_name),
259270
_ => throw new NotSupportedException ($"Internal error: runtime type {JNIEnvInit.RuntimeType} not supported")
260271
};
261272

262-
if (type != null)
273+
if (type != null) {
274+
TypeManagerMapDictionaries.JniToManaged.Add (class_name, type);
263275
return type;
276+
}
264277

265278
if (!JNIEnvInit.IsRunningOnDesktop) {
266279
// Miss message is logged in the native runtime
@@ -285,11 +298,9 @@ static Type monovm_typemap_java_to_managed (string java_type_name)
285298
IntPtr class_ptr = JNIEnv.GetObjectClass (handle);
286299
string? class_name = GetClassName (class_ptr);
287300
lock (TypeManagerMapDictionaries.AccessLock) {
288-
while (class_ptr != IntPtr.Zero && !TypeManagerMapDictionaries.JniToManaged.TryGetValue (class_name, out type)) {
289-
290-
type = GetJavaToManagedType (class_name);
301+
while (class_ptr != IntPtr.Zero) {
302+
type = GetJavaToManagedTypeCore (class_name);
291303
if (type != null) {
292-
TypeManagerMapDictionaries.JniToManaged.Add (class_name, type);
293304
break;
294305
}
295306

0 commit comments

Comments
 (0)