ArrayFactory SAM type / toArray

Aleksey Shipilev aleksey.shipilev at
Thu Sep 20 03:25:56 PDT 2012

Hi Josh,

On 09/20/2012 02:33 AM, Joshua Bloch wrote:
>     I agree with you that most users don't pre-allocate the array.
>      Which makes the existing form of toArray even more unfortunate!
>      Because then the allocation always involves multiple reflective
>     calls.  (Some of which are sometimes optimized by some VMs in some
>     conditions, but none of which are always optimized by all VMs in all
>     conditions.)  So the performance will always be worse in the
>     toArray(T[]) formulation.
> Performance is typically irrelevant.  In the rare cases where it isn't,
> you preallocate.  Warping API for performance is generally a bad idea.

Begging to differ here. Isn't the API the middleground for _both_ user
convenience and library performance? Most users choose API for the
consistency, but more and more users these days ask themselves from the
ground up about the expected performance.

In general sense, I would agree this is a premature optimization type of
thing; but not after you start to deal with concurrency, excess
allocations, and such. Having concise but more-computation-involved API
is OK, but having one which messes with memory more than it should is no
recipe for good performance.

This, by the way, makes me thinking: if ArrayFactory contract is relaxed
to say "provides the candidate for storing the values", i.e. dropping
the referential equality out of the question, we can then do pre-cached
returns from toArray for small collections, and thus completely spare
the allocations on some of the code paths.


More information about the lambda-libs-spec-observers mailing list