Files
spring-boot/core
Phillip Webb 2fffebe214 Reduce garbage of repeated WritableJson.toByteArray() calls
Update the default implementation of `WritableJson.toByteArray()`
to reduce the amount of garbage created from repeated calls.

Prior to this commit, each call would create a new
`ByteArrayOutputStream` and `OutputStreamWriter` to create the
byte array. Writing structured JSON results in many calls to
the `toByteArray()` method, which means we repeatedly create
and destroy the `ByteArrayOutputStream` and `OutputStreamWriter`
objects. Furthermore, both contain buffers that are often
expanded and will overlap with each other.

The updated implementation uses a custom `Appendable`
implementation that uses a single `ByteBuffer` buffer. It also
has a `ThreadLocal` cache so that repeated calls from the same
thread can reuse the buffer. The cache uses a `SoftReference`
to ensure that the JVM can reclaim space if needed (for example,
if a large JSON line was written).

Closes gh-49428
2026-04-30 12:04:39 -07:00
..
2026-04-10 09:56:53 +01:00