Performance: Why DTOs matter
This affects the speed of data transfer between server and client and the efficiency of rendering data in the UI.
Jump into concepts and practice - no test required
public class UserDTO { private String username; private String email; // getters and setters } @GetMapping("/user/{id}") public UserDTO getUser(@PathVariable Long id) { UserEntity user = userRepository.findById(id).orElse(null); if (user == null) return null; UserDTO dto = new UserDTO(); dto.setUsername(user.getUsername()); dto.setEmail(user.getEmail()); return dto; }
public class UserEntity { private Long id; private String username; private String password; private String email; private Date createdAt; // getters and setters } // Controller returns UserEntity directly @GetMapping("/user/{id}") public UserEntity getUser(@PathVariable Long id) { return userRepository.findById(id).orElse(null); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sending full entity | No extra DOM nodes | No reflows from data | Higher paint cost due to larger data | [X] Bad |
| Sending DTO with minimal fields | No extra DOM nodes | No reflows from data | Lower paint cost due to smaller data | [OK] Good |
/user?
@GetMapping("/user")
public UserDTO getUser() {
UserDTO dto = new UserDTO();
dto.setName("Alice");
dto.setAge(30);
return dto;
}public class ProductDTO {
private String name;
private int price;
public ProductDTO(String name, int price) {
this.name = name;
this.price = price;
}
}User with many fields, but you want to expose only id and email in your API response. How should you use a DTO to achieve this cleanly?