Skip to content Are you an AI agent? QIO facts, prices and requests are here

Technology4 min read

Reading a private integer field in .NET 10: 0.25 ns versus 8.96 ns

On a Ryzen 9 5950X running .NET 10, reading a private int took 8.96 ns with reflection and 0.25 ns with UnsafeAccessor, a 35.8-fold difference. On the same CPU with .NET 8, reflection took 33.74 ns, 108.3 times the accessor’s time. The source does not specify whether the integer test cached the field lookup. It reports lookup costs separately for strings.

Reading a private integer field in .NET 10: 0.25 ns versus 8.96 ns

What it looks like in code

The situation is common: a class from someone else's library, a package or the platform itself cannot be edited, yet a private field has to be reached. The habitual route is to get the field description through GetField with non-public binding flags and call GetValue.

The .NET 8 approach looks different. A method is declared as extern static with no body, supplied by the runtime: an UnsafeAccessor attribute with the Field kind and the field name, returning a reference to the field. Because it returns by reference, one declaration covers both reading and writing.

Suppose the library declares class Box { private int _value; }. Import System.Runtime.CompilerServices at the top of the file. Inside a helper class, declare the accessor as follows.

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_value")] static extern ref int Value(Box box);

Given a Box instance named box, read the field with int current = Value(box); or write it with Value(box) = 5; inside the helper.

Techniques like this belong in code after profiling, not before it. We ask to see the measurement where field access is actually visible in the profile. Usually the time turns out to be going into database queries, and the private field has nothing to do with it.

What the benchmark showed

Geronom, the author of the Habr benchmark, ran the comparison on four machines: an Intel Core i9-10900KF, an AMD Ryzen 9 5950X, an Intel Xeon W-2255 and a dual-socket Xeon Silver 4314 system. All x64, with the .NET 8, 9 and 10 runtimes in a single BenchmarkDotNet run. The integer results give one time for reflection on each machine. The author does not say whether that time includes finding the field.

For the separate string test on .NET 10, the author timed reflection two ways. With the field looked up once in advance, reads took 2.9 to 7.8 times as long as UnsafeAccessor across the four machines. Looking up the field on every read raised the ratio to 14.8–40.2. UnsafeAccessor was close to a direct read inside the class.

A private string read takes 0.75 ns with UnsafeAccessor and 11.15 ns with a fresh reflection lookup on the Ryzen 9.
Time per private string read on the Ryzen 9 5950X with .NET 10. Short bar, 0.75 ns with UnsafeAccessor. Tall bar, 11.15 ns with reflection looking up the field on every read.

Why it is that fast

GetValue returns an object. For the int field in this benchmark, the runtime copied the value into a new heap object (boxing), allocating 24 bytes per read. Reading a string returns an existing reference.

UnsafeAccessor works when the method is compiled. The runtime resolves the field once, the first time it compiles the accessor, and inlines an ordinary read by offset. After that the same machine code runs as for a direct field access, so there is simply no difference left to measure.

Where it goes wrong

The price of the speed is the loss of several checks, and three traps are worth knowing in advance.

  • The field name is a string, and the compiler will not catch a typo: the build succeeds and the first call throws MissingFieldException. Reflection returns null from GetField in the same situation, which can be checked earlier.
  • Declare the first parameter using the type that defines the field. For a field inherited from a base class, use the base class as the parameter type. Lookup starts and ends at the declared type.
  • For a struct the first argument must be declared by reference. Otherwise the method receives a copy and a write to the field is lost silently.

When it is actually needed

The honest answer: less often than one would like. If a field is private, the library author usually had a reason, and reaching into it means accepting that the next version may break your code without a word.

The sensible cases are narrow: serialization, frameworks working with foreign objects, tests that need to inspect internal state, and hot code where reflection already showed up in the profile. Everywhere else, look for a public API first, because a nanosecond only matters across millions of calls.

One example in the .NET base class library is ResourceReader, which uses an accessor to reach a BinaryFormatter method.

The takeaway

UnsafeAccessor is a rare case where the faster route is also the simpler one: a single attribute instead of caching field descriptions and emitting code. But it removes exactly the checks that made reflection safe, so it belongs where the cost of access is genuinely visible in measurements.

Sources

  1. A private field in 0.25 nanoseconds, Habr
  2. UnsafeAccessorAttribute, Microsoft Learn
  • .NET
  • UnsafeAccessor
  • Reflection
  • BenchmarkDotNet
  • C#

Follow the journal

New pieces on websites, SEO and AI come out in the QIO journal. Follow in Google, by RSS or in Telegram to get them first.

Read next

How can we help?
Discuss a project