8332842: Optimize empty CopyOnWriteArrayList allocations

Reviewed-by: shade, alanb
This commit is contained in:
John Engebretson 2024-08-14 14:11:53 +00:00 committed by Aleksey Shipilev
parent fbe4f05636
commit a5d948fb98
2 changed files with 184 additions and 4 deletions

View file

@ -100,6 +100,8 @@ public class CopyOnWriteArrayList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8673264195747942595L;
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The lock protecting all mutators. (We have a mild preference
* for builtin monitors over ReentrantLock when either will do.)
@ -128,7 +130,7 @@ public class CopyOnWriteArrayList<E>
* Creates an empty list.
*/
public CopyOnWriteArrayList() {
setArray(new Object[0]);
setArray(EMPTY_ELEMENTDATA);
}
/**
@ -143,6 +145,8 @@ public class CopyOnWriteArrayList<E>
Object[] es;
if (c.getClass() == CopyOnWriteArrayList.class)
es = ((CopyOnWriteArrayList<?>)c).getArray();
else if (c.isEmpty())
es = EMPTY_ELEMENTDATA;
else {
es = c.toArray();
if (c.getClass() != java.util.ArrayList.class)
@ -159,7 +163,10 @@ public class CopyOnWriteArrayList<E>
* @throws NullPointerException if the specified array is null
*/
public CopyOnWriteArrayList(E[] toCopyIn) {
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
if (toCopyIn.length == 0)
setArray(EMPTY_ELEMENTDATA);
else
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
/**
@ -533,6 +540,8 @@ public class CopyOnWriteArrayList<E>
Object[] newElements;
if (numMoved == 0)
newElements = Arrays.copyOf(es, len - 1);
else if (len == 1)
newElements = EMPTY_ELEMENTDATA;
else {
newElements = new Object[len - 1];
System.arraycopy(es, 0, newElements, 0, index);
@ -618,6 +627,11 @@ public class CopyOnWriteArrayList<E>
if (index < 0)
return false;
}
if (len == 1) {
// one element exists and that element should be removed
setArray(EMPTY_ELEMENTDATA);
return true;
}
Object[] newElements = new Object[len - 1];
System.arraycopy(current, 0, newElements, 0, index);
System.arraycopy(current, index + 1,
@ -804,7 +818,7 @@ public class CopyOnWriteArrayList<E>
*/
public void clear() {
synchronized (lock) {
setArray(new Object[0]);
setArray(EMPTY_ELEMENTDATA);
}
}
@ -1022,7 +1036,7 @@ public class CopyOnWriteArrayList<E>
// Read in array length and allocate array
int len = s.readInt();
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, len);
Object[] es = new Object[len];
Object[] es = (len == 0 ? EMPTY_ELEMENTDATA : new Object[len]);
// Read in all elements in the proper order.
for (int i = 0; i < len; i++)