Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EnumTypeAdapter constructor optimization #2734

Merged
merged 3 commits into from
Sep 3, 2024
Merged

Conversation

esaulpaugh
Copy link
Contributor

Purpose

Improve the runtime performance of EnumTypeAdapter(Class).

Description

Eliminate the temporary ArrayList in favor of array truncation via <T> java.util.Arrays.copyOf(T[],int).

Copy link
Member

@eamonnmcmanus eamonnmcmanus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that is neat! Just one request.

}
}

Field[] constantFields = constantFieldsList.toArray(new Field[0]);
AccessibleObject.setAccessible(constantFields, true);
// Trim the array to the new length
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My initial thought was that most of the time you won't need to do this. Every call to getDeclaredFields() returns a new array and if there are no fields that are not enum constants then you can just use that array as is. However, with javac at least, it turns out that there is always a private $VALUES field which is an array that is cloned every time values() is called on the enum. So perhaps add a further note like "This will always be needed because of the $VALUES field."

Copy link
Contributor Author

@esaulpaugh esaulpaugh Sep 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call; comment added.

Also, the enum constants all seem to appear first among the declared fields, which would allow reusing the unmodified array (up to the first non-enum constant), but the documentation warns not to rely on that behavior. But at least branch prediction should be good.

@eamonnmcmanus eamonnmcmanus merged commit 4e4c2fd into google:main Sep 3, 2024
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants