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

Performance improvement by fixing hashCode() #849

Merged
merged 1 commit into from
Jun 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/main/java/org/testng/internal/BaseTestMethod.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public abstract class BaseTestMethod implements ITestNGMethod {
private int m_priority;

private XmlTest m_xmlTest;
private Object m_instance;
private final Object m_instance;

/**
* Constructs a <code>BaseTestMethod</code> TODO cquezel JavaDoc.
Expand Down Expand Up @@ -428,7 +428,11 @@ public boolean equals(Object obj) {
*/
@Override
public int hashCode() {
return m_method.hashCode();
int hash = m_method.hashCode();
if (m_instance != null) {
hash = hash * 31 + m_instance.hashCode();
}
Comment on lines +432 to +434
Copy link
Contributor

Choose a reason for hiding this comment

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

BaseTestMethod#equals uses identity comparison like getInstance() == other.getInstance(), so the hashCode implementation should use identity hashCode rather than user-provided implementation.

In other words, this should be System.identityHashCode(m_instance)

Other than that, the change is a clear improvement with little-to-no risk, so it is safe to merge if m_instance.hashCode() is replaced with identityHashCode

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm confused. How is this a performance improvement? It does more work than the previous implementation.

Copy link
Contributor

Choose a reason for hiding this comment

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

Extra work is negligible, and the new implementation produces better hash codes, so there are less chances for collision in

   at java.util.HashSet.add
   at org.testng.internal.DynamicGraph.setStatus 
   at org.testng.internal.thread.graph.GraphThreadPoolExecutor.setStatus

return hash;
}

protected void initGroups(Class<? extends ITestOrConfiguration> annotationClass) {
Expand Down