From 8061303a6fa8ce849c1e25191e02e64093f1be75 Mon Sep 17 00:00:00 2001 From: brharrington Date: Wed, 3 Jan 2024 18:47:02 -0600 Subject: [PATCH] cache hash code for Query.In (#1106) In some cases it can be a big set of values and recomputing in the query index to do map looks has a high overhead. --- .../main/java/com/netflix/spectator/atlas/impl/Query.java | 7 +++++++ .../java/com/netflix/spectator/atlas/impl/QueryTest.java | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Query.java b/spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Query.java index eb598d487..6e4f7c202 100644 --- a/spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Query.java +++ b/spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Query.java @@ -567,11 +567,14 @@ final class In implements KeyQuery { private final String k; private final Set vs; + private final int cachedHashCode; + /** Create a new instance. */ In(String k, Set vs) { Preconditions.checkArg(!vs.isEmpty(), "list of values for :in cannot be empty"); this.k = Preconditions.checkNotNull(k, "k"); this.vs = Preconditions.checkNotNull(vs, "vs"); + this.cachedHashCode = calculateHashCode(); } @Override public String key() { @@ -618,6 +621,10 @@ public Set values() { } @Override public int hashCode() { + return cachedHashCode; + } + + private int calculateHashCode() { int result = k.hashCode(); result = 31 * result + vs.hashCode(); return result; diff --git a/spectator-reg-atlas/src/test/java/com/netflix/spectator/atlas/impl/QueryTest.java b/spectator-reg-atlas/src/test/java/com/netflix/spectator/atlas/impl/QueryTest.java index a91345453..0d5cb0e93 100644 --- a/spectator-reg-atlas/src/test/java/com/netflix/spectator/atlas/impl/QueryTest.java +++ b/spectator-reg-atlas/src/test/java/com/netflix/spectator/atlas/impl/QueryTest.java @@ -116,6 +116,10 @@ public void inEqualsContract() { EqualsVerifier .forClass(Query.In.class) .suppress(Warning.NULL_FIELDS) + .withCachedHashCode( + "cachedHashCode", + "calculateHashCode", + new Query.In("k", Collections.singleton("v"))) .verify(); }