Repository navigation
Description
Currently, Java.Interop.JniPeerMembers member lookups are backed via dictionary lookup with string as the key-type, e.g.
https://github.com/xamarin/java.interop/blob/7dc270dbb83948b278bee38fc83bf9ae5cd42a7e/src/Java.Interop/Java.Interop/JniPeerMembers.JniStaticMethods.cs#L18
https://github.com/xamarin/java.interop/blob/7dc270dbb83948b278bee38fc83bf9ae5cd42a7e/src/Java.Interop/Java.Interop/JniPeerMembers.JniStaticMethods.cs#L25-L36
This works, and provides a reasonably "user-friendly" interface, but has hidden performance implications:
JniPeerMembers.GetNameAndSignature()allocates strings, which creates "garbage" objects, as they're not long-lived: https://github.com/xamarin/java.interop/blob/7dc270dbb83948b278bee38fc83bf9ae5cd42a7e/src/Java.Interop/Java.Interop/JniPeerMembers.cs#L183-L188- The dictionary lookup requires traversing the entire
encodedMemberstring, which is a (usually fast!) O(n) operation. - There is "implicit" marshaling overhead, as e.g.
JniType.GetStaticMethod()involves a P/Invoke, which marshals a UTF-16stringinstance to a UTF-8 native string: https://github.com/xamarin/java.interop/blob/7dc270dbb83948b278bee38fc83bf9ae5cd42a7e/src/Java.Interop/Java.Interop/JniType.cs#L252-L257
(Note: this still appears to contribute ~2ms to Xamarin.Android app startup, so it's not a huge source of performance implications, but it is A Thing™ to consider…)
These methods are usually invoked via generator-emitted code, such as:
namespace Android.App {
public partial class Activity {
public static unsafe long InstanceCount {
[Register ("getInstanceCount", "()J", "")]
get {
const string __id = "getInstanceCount.()J";
try {
var __rm = _members.StaticMethods.InvokeInt64Method (__id, null);
return __rm;
} finally {
}
}
}
}
}We could improve this by:
- Pre-compute a hashcode value.
- Use
Span<T>types, which - Use
byteinstead ofchar, and - Contain embedded nulls
Thus, instead of:
const string __id = "getInstanceCount.()J";
var __rm = _members.StaticMethods.InvokeInt64Method (__id, null);We would instead have generator emit:
static readonly int hash_getInstanceCount = JniPeerMembers.ComputeHash ("getInstanceCount.()J");
…
ReadOnlySpan<byte> __id = new stackalloc {
(byte) 'g',
(byte) 'e',
…
(byte) 't',
(byte) 0, // terminates `getInstanceCount`
(byte) '.'
(byte) '(',
(byte) ')',
(byte) 'J',
(byte) 0, // terminates `()J`
};
var __rm = _members.StaticMethods.InvokeInt64Method (hash_getInstanceCount, __id, null);JniEnvironment.StaticMethods.GetStaticMethodID() & co. could then be overloaded to take ReadOnlySpan<T> parameters (as overloads to the current string parameters).
TODO: verify that ReadOnlySpan<byte> as a P/Invoke parameter (1) works, and (2) passes the data as-is, no copy or marshaling involved.
Doing all this would remove the need to marshal anything: everything would already be UTF-8, because that's what generator's stackalloc would contain, so there's no System.String-to-const char* marshaling involved (as is currently required). This would also help with the embedded Dictionary<string, JniMethodInfo> lookup, which could now become a Dictionary<int, JniMethodInfo> lookup (as the hash is pre-computed).
On the downside, this would be a kind-of ABI break: binding assemblies using these new members couldn't be used on older Xamarin.Android SDKs/etc. (This is where multi-targeting solves everything.)
Activity
jonathanpeppers commentedon Oct 11, 2022
Apparently this works in C# 11:
So maybe we can avoid the
stackallocsyntax?https://devblogs.microsoft.com/dotnet/csharp-11-preview-updates/#utf-8-string-literals
simonrozsival commentedon Feb 12, 2026
Experiment summary by Copilot:
PoC: UTF-8
ReadOnlySpan<byte>overloads for JNI lookupsWe prototyped the approach described in this issue using C# UTF-8 string literals (
"java/lang/Object"u8), which are available since C# 11 and avoid thestackallocsyntax entirely (as @jonathanpeppers noted). Here's a summary of what we did, how we benchmarked it, and what we found.What we changed in the product
We added
ReadOnlySpan<byte>overloads to the lower-level JNI lookup APIs, guarded by#if FEATURE_JNIENVIRONMENT_JI_FUNCTION_POINTERS:JniEnvironment.Types.FindClass(ReadOnlySpan<byte>)— bypassesMarshal.StringToCoTaskMemUTF8entirely; usesfixedpinning to pass the span directly to JNI'sFindClassJniType(ReadOnlySpan<byte>)constructor +GetCachedJniType(ReadOnlySpan<byte>)JniType:GetInstanceMethod,GetStaticMethod,GetInstanceField,GetStaticField,GetConstructor, and theirGetCached*variants — all acceptReadOnlySpan<byte>for name and signatureAll overloads are purely additive — existing
string-based APIs remain unchanged (no API/ABI break). We also updated ~5 internal call sites to useu8literals with#if/#elsefallbacks.The
JniPeerMemberslayer (dictionary caches,GetReplacementMethodInfo) was not changed in this PoC — it requires refactoring string-keyed dictionaries and a public virtual API, which is a larger effort matching points 1-2 from the original proposal.How we benchmarked
We created a BenchmarkDotNet project (
tests/Java.Interop-Benchmarks/) running against a desktop JVM. Key setup decisions:InProcessNoEmitToolchain: BDN's default out-of-process toolchain can't rebuild the native cmake-based java-interop libraryLaunchCount=1: JDK only allows oneJNI_CreateJavaVMper process; a shared JVM instance is reused across benchmark classesShortRunjob:IterationCount=5, WarmupCount=3— sufficient for stable results on JNI callsMemoryDiagnoser: Tracks managed heap allocations per operationCritical finding:
ManagedObjectReferenceManagerinvalidates benchmarksOur initial runs showed 42KB allocated per
FindClasscall — wildly unrealistic. The root cause:ManagedObjectReferenceManager(used byTestJVM) was capturing full managed stack traces (GetCurrentManagedThreadStackTrace(skipFrames:2, fNeedFileInfo:true)) on every JNI reference create/delete, allocating ~30KB of strings per operation.This happens because the constructor reads
JAVA_INTEROP_GREF_LOGindependently fromTestJVM.GetLogOutput()— even with the env var set to "suppress",ManagedObjectReferenceManagersees a non-empty string and creates aStreamWriterto a file literally named "suppress".Fix: We created a
NoOpObjectReferenceManager(sealed subclass ofJniRuntime.JniObjectReferenceManagerthat only overridesGlobalReferenceCount/WeakGlobalReferenceCountto return 0) and passed it viaTestJVMOptions.ObjectReferenceManager. This might be worth noting for anyone else benchmarking JNI operations.Results (Release build, NoOp ObjectReferenceManager)
string(ns)u8span (ns)Observations:
Marshal.StringToCoTaskMemUTF8+Marshal.ZeroFreeCoTaskMemUTF8calls.stringpath's marshal cost is invisible toMemoryDiagnoser—CoTaskMemAlloc/CoTaskMemFreeoperate on the native heap, not the managed GC heap. The real savings are in CPU time (no transcoding, no native alloc/free) and in native heap pressure.JniMethodInfo/JniFieldInfo/JniTypeclass instances themselves — same for both paths, unavoidable without converting these to structs (API break).Side note: dead-weight fields on JNI primitive types
While investigating allocations, we audited fields on the JNI info types and found some that appear unused:
JniMethodInfo.IsStatic(publicbool, 1B + 7B padding = 8B effective): Set in constructor, never read by anything — not internally in java-interop, not in android-main, not in any test. Zero references via LSPfindReferences. The caller already knows whether they calledGetStaticMethodvsGetInstanceMethod.JniFieldInfo.IsStatic(same pattern): Also never read by anything. Same reasoning — the caller chose the static vs instance API.JniType.registered(bool, 8B effective with padding): Used only byRegisterWithRuntime()/UnTrack()for tracking JNI global references duringJniRuntimeshutdown. Zero usage in android-main — Android processes just die, they never cleanly shut down the runtime. Only relevant for desktop JVM scenarios.These are small per-instance, but in a MAUI app with thousands of bound types, methods, and fields, the 8B overhead per instance adds up.
IsStaticin particular seems like it could be deprecated since it has zero consumers. Removing it would shrinkJniFieldInfofrom 32B → 24B andJniMethodInfofrom 48B → 40B.Add ReadOnlySpan<byte> overloads for JNI member lookups
Add ReadOnlySpan<byte> overloads for JNI member lookups
Add ReadOnlySpan<byte> overloads for JNI member lookups
Add `ReadOnlySpan<byte>` overloads for JNI member lookups (#1393)
dotnet-policy-service commentedon Jul 1, 2026
We suspect this issue is stale and no longer relevant. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.
dotnet-policy-service commentedon Jul 15, 2026
This issue will now be closed since it had been marked "possibly-stale" but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.