Quick revision
The short answer
The mapper is paying for a field lookup by name on every object, so the first fix is to look each Field up once per class and cache it, ideally in a ClassValue. Beyond caching, we can store a VarHandle or MethodHandle per field for faster access, generate functional accessors with LambdaMetafactory, or remove run-time reflection completely by generating the mapping code at compile time with MapStruct or an annotation processor. Whatever we choose, we confirm the gain with JMH and a production profile afterwards.
What to remember
In this answer, we saw that the mapper spends its time looking up the same fields by name for every object. Caching the fields once per class, preferably in a ClassValue so classes can still be unloaded, removes most of the cost. Beyond caching, VarHandles or MethodHandles give faster access, LambdaMetafactory turns getters into near-direct functional calls, and MapStruct or another annotation processor removes run-time reflection entirely. We finish by proving the gain with JMH and the production profiler.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The mapper is paying for a field lookup by name on every object, so the first fix is to look each Field up once per class and cache it, ideally in a ClassValue. Beyond caching, we can store a VarHandle or MethodHandle per field for faster access, generate functional accessors with LambdaMetafactory, or remove run-time reflection completely by generating the mapping code at compile time with MapStruct or an annotation processor. Whatever we choose, we confirm the gain with JMH and a production profile afterwards.
Why this question is asked
Hand-written mappers that copy fields between objects are common in services that grew before a mapping library was chosen. They work well until traffic grows, and then a profiler shows a surprising slice of CPU in java.lang.reflect. Interviewers use this scenario to see whether we can find the real cost, fix it in steps, and know the range of tools from simple caching to code generation. In this answer, we will look at why the current mapper is slow, apply the caching fix, then go further with VarHandles, LambdaMetafactory and compile-time generation, and finish with how to prove the gain.
1What the Mapper Is Doing Today
A typical mapper of this kind looks like the code below. For every source object, and for every property, it asks the class for a field by name, makes it accessible and reads it. Class.getDeclaredField searches the declared fields, runs access checks and returns a new copy of the Field object every time, because Field objects are mutable. Then setAccessible repeats a module check, and Field.get boxes primitive values into objects.
Notice that the lookup result never changes: the Order class has the same fields for the whole life of the JVM. So most of the 15 percent is spent recomputing the same answer, and that is the first thing we remove.
2Fix 1: Cache the Fields Once per Class
The cache key is the class, and the value is the list of prepared accessors for that class. A ConcurrentHashMap<Class<?>, ...> works, but ClassValue is a better fit. ClassValue is a JDK class made exactly for attaching a computed value to a Class: we override computeValue, and get(cls) computes it once per class and then returns the stored value.
The reason ClassValue is better than a map is class unloading. A static ConcurrentHashMap keeps a strong reference to every Class it has seen, so classes loaded by a plugin or a redeployed web application can never be unloaded, and their class loaders leak. ClassValue stores the value with the class itself, so when the class becomes unreachable, the cached value goes with it. It is also designed for very fast reads on the hot path.
In most cases this step alone removes the bulk of the cost. But Field.get still boxes and still goes through the reflection machinery, so if the mapper remains hot, we can go further.
3Fix 2: Store VarHandles or MethodHandles per Field
A VarHandle is a typed reference to a variable, such as a field, that we can read and write through methods like get and set. A MethodHandle is the same idea for methods and constructors. Both come from a MethodHandles.Lookup, and both are optimised by the JIT much better than Field.get, especially when they are held in a final field.
privateLookupIn gives access to private fields, but only if the target package is open to our module; for classes on the class path this is the case. The handles are cached in the same ClassValue as before. Because our generic mapper stores them in an array rather than in static final fields, the JIT cannot fully constant-fold them, so the gain over cached Field objects is real but smaller than in a benchmark with a single static final handle. That is one reason to measure rather than assume.
4Fix 3: Functional Accessors With LambdaMetafactory
LambdaMetafactory is the JDK class that javac uses behind every lambda. We can call it ourselves to turn a method handle for a getter into a real Function<Order, Object> implementation. Calling that function is an ordinary interface call, which the JIT inlines like any other, so the speed is close to a direct call.
But there is a catch: LambdaMetafactory needs a method, so it works with getters, not with raw fields. The lookup must also have access to the target class, and the code is harder to read and debug than plain reflection. It is worth it for a small, central component that runs constantly, not for every mapper in the codebase.
5Fix 4: Generate the Mapping Code at Compile Time
The most complete fix is to stop reflecting at run time. MapStruct is an annotation processor: we declare an interface, and at compile time it writes a plain Java class that calls getters and setters directly. There is no lookup, no boxing and nothing for the JIT to guess about, and mistakes such as an unmapped property become compile warnings or errors.
| Option | Speed | Cost and limits |
|---|---|---|
Cache Field per class (ClassValue) | removes the lookup cost | small change; still boxes |
VarHandle or MethodHandle per field | faster access | needs open packages; moderate change |
LambdaMetafactory accessors | close to direct calls | getters only; complex code |
| MapStruct or annotation processor | direct calls, no reflection | migration effort; build step |
Generated code also works with GraalVM native images and Spring AOT without extra reflection metadata. The cost is a migration: mappings with custom rules need annotations or small methods, and the team has to learn the tool. For a mapper that already costs 15 percent of CPU, that is usually a good trade.
6Proving the Gain
We verify in two places. First, a JMH benchmark that maps a realistic object, with -prof gc to show allocation per mapping, comparing the old mapper with each candidate. Second, the production profile after release, with the same load, to check that the 15 percent has really gone and has not simply moved, for example into garbage collection. Async-profiler or Java Flight Recorder both show this. If caching alone brings the mapper below 1 or 2 percent, we may stop there and keep the code simple.
7Follow-up questions
Why is ClassValue a good fit for per-class caches?
ClassValue is made for exactly this: a value computed once for each Class and stored with it. Reads are fast and thread-safe, computeValue runs lazily, and the value does not keep the class alive. A static map keyed by Class holds strong references, so classes from redeployed applications or plugins, and their whole class loaders, can never be unloaded, which is a classic memory leak. With ClassValue, the cached accessors disappear together with the class.
Would you start with MapStruct straight away?
Usually not. Caching per class is a small, safe change that often removes most of the cost in an hour. I would ship that first, measure, and then plan MapStruct if the mapper is still hot or if we want compile-time checks and native-image support anyway. Changing tools is easier to justify once the quick win has been taken and measured.
Are VarHandles always faster than Field.get?
Not always by a large margin. They are fastest when the JIT can treat the handle as a constant, such as a static final field. In a generic mapper that keeps handles in arrays, the gain is smaller, and since JDK 18 Field.get itself is built on method handles. That is why we benchmark the actual mapper rather than a toy example.
8Conclusion
In this answer, we saw that the mapper spends its time looking up the same fields by name for every object. Caching the fields once per class, preferably in a ClassValue so classes can still be unloaded, removes most of the cost. Beyond caching, VarHandles or MethodHandles give faster access, LambdaMetafactory turns getters into near-direct functional calls, and MapStruct or another annotation processor removes run-time reflection entirely. We finish by proving the gain with JMH and the production profiler.
Open with
The profile tells me the mapper calls getDeclaredField and setAccessible for every object, so it repeats a search whose answer never changes. My first step would be to compute the accessors once per class and cache them.
Then, if they want more
I would use ClassValue rather than a static ConcurrentHashMap keyed by Class, because ClassValue stores the value with the class and does not stop classes from being unloaded, so we avoid leaking class loaders on redeploy. That fix is small and usually removes most of the cost.
If the mapper is still hot, I would replace Field.get with VarHandles or MethodHandles obtained once through privateLookupIn, which the JIT optimises better and which avoid some of the boxing. For getters, LambdaMetafactory can build real Function objects that run at almost direct-call speed, though the code is more complex.
The most complete option is to stop using run-time reflection and generate the mapping at compile time with MapStruct or our own annotation processor, which also helps with native images.
Whichever I choose, I would benchmark the real mapper with JMH, including allocation with the gc profiler, and then confirm in production that the CPU share has really dropped rather than moved into GC.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A profiler shows 15 percent of CPU in a hand-written mapper that uses...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/0a5efc3903/