RFR: 8371164: ArrayList.addAll() optimizations

Claes Redestad redestad at openjdk.org
Tue Nov 4 18:13:26 UTC 2025


On Tue, 4 Nov 2025 14:47:01 GMT, jengebr <duke at openjdk.org> wrote:

>> src/java.base/share/classes/java/util/ArrayList.java line 753:
>> 
>>> 751:      */
>>> 752:     public boolean addAll(Collection<? extends E> c) {
>>> 753:         if (c.getClass() == ArrayList.class) {
>> 
>> Consider simplifying this to reduce code duplication:
>> 
>> Object[] a;
>> int newNum;
>> if (c.getClass() == ArrayList.class) {
>>     ArrayList<?> src = (ArrayList<?>) c;
>>     a = src.elementData;
>>     numNew = src.size;
>> } else {
>>     a = c.toArray();
>>     numNew = a.length;
>> }
>> modCount++;
>> ...
>
> Interestingly, this hurt the fast-path about 5%, but the control case about 35%.  I'm going to leave it as-is on the basis of data.

Ok, if the split helps the JIT peel and optimize better some amount of code duplication can be fine, but maybe then split out the two implementations to separate methods (to help inlining) and comment that the code duplication is intentional and should be handled with care.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/28116#discussion_r2491610407


More information about the core-libs-dev mailing list