about Enum.values() memory allocation

Brian Goetz brian.goetz at oracle.com
Wed Jul 25 19:48:03 UTC 2018


This is essentially an API design bug; because values() returns an 
array, and arrays are mutable, it must copy the array every time.  
Otherwise some miscreant could change the contents of this array, and 
other consumers of `values()` would see wrong data.

There are a number of ways this could be improved, each with their pros 
and cons:

  - Add a new method, valuesAsList(), which would return an immutable 
list which could be cached and shared.  (Arguably this is what 
Enum::values should have done in the first place.)  Easy to add, but 
puts the burden on users to change their code.

  - Wait for the JVM to support frozen arrays, and then have values() 
return a frozen array.  This would allow sharing.  It is a 
behavior-incompatible change, but one we could probably justify.

  - Have the compiler recognize that the array returned from values() is 
confined to a scope from which it does not escape and is not mutated, 
and if so, perform some sort of transformation (such as the one 
suggested in the mail you link to.)

  - Similar to the previous, but using JIT optimizations.


I'm not too hot on either the static or dynamic compiler transformation 
routes; I think the return-on-complexity is not that good.  The new 
method is the easiest, but it might look silly if the frozen arrays 
solution comes around soon.

On 7/25/2018 1:23 AM, nezih yigitbasi wrote:
> Hi,
> I recently noticed in our app that Enum.values() allocates a 
> significant amount of memory when called in a tight loop as it clones 
> the constant values array (which is probably for immutability, and I 
> can understand that). I found that the same issue has been discussed 
> back in 2012: 
> http://mail.openjdk.java.net/pipermail/compiler-dev/2012-March/004210.html 
>
>
> Are there any plans to address this issue going forward?
>
> Thanks!
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20180725/6d808ca3/attachment.html>


More information about the compiler-dev mailing list