Performance: Why REST controllers are essential
REST controllers impact server response time and client rendering speed by structuring API endpoints efficiently.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class UserController { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Charlie"); } }
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class UserController { @RequestMapping("/users") public String getUsers() { // returns view name, not JSON data return "users"; } }
| Pattern | Server Processing | Network Payload | Client Rendering | Verdict |
|---|---|---|---|---|
| @Controller returning views | High (renders HTML) | Large (full HTML pages) | Slower (parsing HTML) | [X] Bad |
| @RestController returning JSON | Low (serializes data) | Small (JSON payload) | Faster (direct data use) | [OK] Good |
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
User user = new User("Alice", 30);
return user;
}
}@RestController
public class UserController {
public List<User> getUsers() {
return List.of(new User("Bob", 25), new User("Carol", 28));
}
}Pass the test and this pattern moves unknown