Skip to content

Commit 8d9e12d

Browse files
authored
Pre computing hash code for WeightedRouting to avoid recomputing it (#13099)
WeightedRoutingKey is used as key in the HashMap to retreive the shard routings, for every usage the hash key is computed. WeightedRoutingKey internally uses WeightedRouting. As the number of the shards getting queried increases, the computation cost goes high. Computing the hash key during object creation as the object is immutable and using it through out the object thus saving on the additional computation. Signed-off-by: Prabhakar Sithanandam <prabhakar.s87@gmail.com>
1 parent 221e981 commit 8d9e12d

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

server/src/main/java/org/opensearch/cluster/routing/WeightedRouting.java

+10-10
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import org.opensearch.core.common.io.stream.Writeable;
1515

1616
import java.io.IOException;
17+
import java.util.Collections;
1718
import java.util.HashMap;
1819
import java.util.Map;
1920
import java.util.Objects;
@@ -25,27 +26,26 @@
2526
*/
2627
@PublicApi(since = "2.4.0")
2728
public class WeightedRouting implements Writeable {
28-
private String attributeName;
29-
private Map<String, Double> weights;
29+
private final String attributeName;
30+
private final Map<String, Double> weights;
31+
private final int hashCode;
3032

3133
public WeightedRouting() {
32-
this.attributeName = "";
33-
this.weights = new HashMap<>(3);
34+
this("", new HashMap<>(3));
3435
}
3536

3637
public WeightedRouting(String attributeName, Map<String, Double> weights) {
3738
this.attributeName = attributeName;
38-
this.weights = weights;
39+
this.weights = Collections.unmodifiableMap(weights);
40+
this.hashCode = Objects.hash(this.attributeName, this.weights);
3941
}
4042

4143
public WeightedRouting(WeightedRouting weightedRouting) {
42-
this.attributeName = weightedRouting.attributeName();
43-
this.weights = weightedRouting.weights;
44+
this(weightedRouting.attributeName(), weightedRouting.weights);
4445
}
4546

4647
public WeightedRouting(StreamInput in) throws IOException {
47-
attributeName = in.readString();
48-
weights = (Map<String, Double>) in.readGenericValue();
48+
this(in.readString(), (Map<String, Double>) in.readGenericValue());
4949
}
5050

5151
public boolean isSet() {
@@ -70,7 +70,7 @@ public boolean equals(Object o) {
7070

7171
@Override
7272
public int hashCode() {
73-
return Objects.hash(attributeName, weights);
73+
return hashCode;
7474
}
7575

7676
@Override

0 commit comments

Comments
 (0)