Skip to content

Commit 4e4c2fd

Browse files
authored
EnumTypeAdapter constructor optimization (#2734)
* EnumTypeAdapter constructor optimization * reuse the fields array * add comment about the necessity of unconditionally trimming the fields array
1 parent 7c55d8b commit 4e4c2fd

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

gson/src/main/java/com/google/gson/internal/bind/EnumTypeAdapter.java

+10-6
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import java.io.IOException;
2828
import java.lang.reflect.AccessibleObject;
2929
import java.lang.reflect.Field;
30-
import java.util.ArrayList;
30+
import java.util.Arrays;
3131
import java.util.HashMap;
3232
import java.util.Map;
3333

@@ -59,17 +59,21 @@ private EnumTypeAdapter(final Class<T> classOfT) {
5959
// Uses reflection to find enum constants to work around name mismatches for obfuscated
6060
// classes
6161
Field[] fields = classOfT.getDeclaredFields();
62-
ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
62+
int constantCount = 0;
6363
for (Field f : fields) {
64+
// Filter out non-constant fields, replacing elements as we go
6465
if (f.isEnumConstant()) {
65-
constantFieldsList.add(f);
66+
fields[constantCount++] = f;
6667
}
6768
}
6869

69-
Field[] constantFields = constantFieldsList.toArray(new Field[0]);
70-
AccessibleObject.setAccessible(constantFields, true);
70+
// Trim the array to the new length. Every enum type can be expected to have at least
71+
// one declared field which is not an enum constant, namely the implicit $VALUES array
72+
fields = Arrays.copyOf(fields, constantCount);
7173

72-
for (Field constantField : constantFields) {
74+
AccessibleObject.setAccessible(fields, true);
75+
76+
for (Field constantField : fields) {
7377
@SuppressWarnings("unchecked")
7478
T constant = (T) constantField.get(null);
7579
String name = constant.name();

0 commit comments

Comments
 (0)