Add special handling for 0 and 1 size Guava immutable collections by olivergillespie · Pull Request #215 · FasterXML/jackson-datatypes-collections (original) (raw)

We do not need to create a Builder for the cases of 0 or 1 elements in a collection, and avoiding it reduces allocation and init work. I saw this in an allocation profile from an application I have which processes a lot of 1-element collections. I appreciate that this is somewhat specialized, but I don't think it hurts the code much when it doesn't apply and provides a nice benefit when it does.

Results from a simple benchmark with Corretto 25.0.1 on Linux x86:

Execution time (ns/op)

Benchmark Baseline Improved Change
empty 28 ± 1.5 27 ± 0.84 within error
oneElement 59 ± 13 50 ± 1.6 -15%
twoElements 85 ± 1.5 73 ± 0.52 -14%
thousandElements 26000 ± 2000 27000 ± 5100 within error

Allocations (bytes/op)

Benchmark Baseline Improved Change
empty 16 16 0
oneElement 64 32 -50%
twoElements 88 56 -36%
thousandElements 18000 18000 0

Nice reduction as expected for one element and no regression I can see for the general case. Surprisingly also a similar benefit for two elements, this turns out to be from Hotspot eliding the Builder creation all by itself. That does suggest there might a different approach, just restructuring to be more amenable to escape analysis in general without explicitly special-casing, but that's more fragile and I don't think this is too ugly.

Passes existing tests.