Skip to content

Performance: Optimize toString() methods with StringBuilder #4012

@cwangg897

Description

@cwangg897

Expected Behavior

The toString() methods in ContainerProperties and ConsumerProperties should use StringBuilder for efficient string building, resulting in O(n) memory complexity and minimal temporary object creation during configuration debugging.

Current Behavior

Both ContainerProperties.toString() and ConsumerProperties.renderProperties() use extensive string concatenations (50+ total) with the + operator:

// ContainerProperties.toString() - 40+ concatenations
return "ContainerProperties [" + renderProperties() + "\n ackMode=" + this.ackMode + ...

// ConsumerProperties.renderProperties() - 10+ concatenations
return renderTopics() + "\n pollTimeout=" + this.pollTimeout + ...

This creates O(n²) memory complexity and excessive temporary String objects, causing performance issues during configuration logging and debugging.

Related Code Locations

  • spring-kafka/src/main/java/org/springframework/kafka/listener/ContainerProperties.java:toString()
  • spring-kafka/src/main/java/org/springframework/kafka/listener/ConsumerProperties.toString()

Context
This issue affects Spring Boot applications during:

  • Container startup when configurations are logged
  • Debugging sessions when examining container properties
  • Troubleshooting scenarios requiring configuration dumps

The performance impact is noticeable in applications with frequent configuration logging or debug-level logging enabled.

I'm trying to improve the debugging experience for Spring Kafka users by eliminating unnecessary memory allocations and GC pressure.

Current workaround: Avoid calling toString() in production, but this limits debugging capabilities.

I have already implemented the StringBuilder solution and can provide a PR if this improvement is welcomed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions