0
0
Spring Bootframework~8 mins

Entity to DTO mapping in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: Entity to DTO mapping
MEDIUM IMPACT
This affects the server response time and the size of data sent to the client, impacting page load speed and interaction responsiveness.
Mapping database entities directly to API responses
Spring Boot
public List<UserDTO> getUsers() {
    return userRepository.findAll().stream()
        .map(user -> new UserDTO(user.getId(), user.getName()))
        .collect(Collectors.toList());
}
Sends only required fields, reducing payload size and improving serialization speed.
📈 Performance GainReduces payload size by up to 50%, speeds up JSON serialization and client rendering
Mapping database entities directly to API responses
Spring Boot
public List<User> getUsers() {
    return userRepository.findAll();
}
Returns full entity objects including unnecessary fields, increasing payload size and exposing internal data.
📉 Performance CostIncreases payload size by 20-50%, blocks rendering longer due to larger JSON parsing
Performance Comparison
PatternCPU OverheadPayload SizeSerialization TimeVerdict
Direct entity returnLowHighHigh[X] Bad
Manual DTO mappingMediumMediumMedium[!] OK
Library-based DTO mappingLowLowLow[OK] Good
DTO with nested full collectionsHighVery HighVery High[X] Bad
DTO with summary fields onlyLowLowLow[OK] Good
Rendering Pipeline
Entity to DTO mapping affects the server-side serialization stage before data is sent to the browser, impacting how quickly the browser can start rendering content.
Server Processing
Network Transfer
Browser Parsing
⚠️ BottleneckServer Processing due to inefficient mapping and large payload serialization
Core Web Vital Affected
LCP
This affects the server response time and the size of data sent to the client, impacting page load speed and interaction responsiveness.
Optimization Tips
1Always map entities to DTOs to send only necessary data.
2Avoid eager mapping of large nested collections in DTOs.
3Use mapping libraries to improve performance and maintainability.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance benefit of using DTOs instead of returning entities directly?
AMore complex code improves security
BSmaller payload size reduces load time
CEntities are faster to serialize
DDTOs increase server CPU usage
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, click on API response, and inspect the size and content of JSON payload.
What to look for: Look for large payload sizes and long waiting times indicating heavy or inefficient data transfer.