Expensive Serialization in Loop¶
Rule details
| Rule ID | expensive-serialization-in-loop |
| Severity | WARNING — likely performance problem |
| Confidence | MEDIUM — likely correct, some context-dependent |
| Category | Loop amplifiers |
| Complexity | O(n·serialize) → O(n) |
Description¶
Detects serialization or deserialization calls inside loops. Operations like writeValueAsString(), readValue(), or JSON.stringify() are themselves O(n) over the object graph — calling them inside a loop compounds the cost.
Typical¶
After¶
String json = objectMapper.writeValueAsString(orders); // Serialize the whole batch once
sendBatch(json);
When individual serialization is required, consider whether the loop itself is necessary — often the consumer can accept a batch.
Suggestion¶
Move serialization outside the loop, or use batch serialization