Java / MapStruct Java Interview questions part 2
How can you optimize MapStruct-generated mapping performance?
Because MapStruct already avoids reflection, most performance gains come from how the mapping methods themselves are structured rather than from MapStruct-specific tuning.
- Reuse mapper instances - obtain a mapper once (via
Mappers.getMapperor DI) instead of creating new instances per call. - Avoid unnecessary object allocation - prefer
@MappingTargetupdate methods when mutating existing objects instead of always constructing new ones. - Keep custom expressions and default methods lightweight - since they run inline, an expensive default method becomes an expensive part of every mapping call.
- Avoid deep unnecessary nested mapping chains - flatten DTOs where the extra nesting isn't needed downstream.
In practice, a well-written MapStruct mapper rarely shows up as a hotspot in profiling, since the generated code is on par with hand-written field assignments.
More Related questions...