Skip to content

Commit

Permalink
Pre computing hash code for WeightedRouting to avoid recomputing it (#…
Browse files Browse the repository at this point in the history
…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 <[email protected]>
  • Loading branch information
backslasht authored Apr 6, 2024
1 parent 221e981 commit 8d9e12d
Showing 1 changed file with 10 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.opensearch.core.common.io.stream.Writeable;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Expand All @@ -25,27 +26,26 @@
*/
@PublicApi(since = "2.4.0")
public class WeightedRouting implements Writeable {
private String attributeName;
private Map<String, Double> weights;
private final String attributeName;
private final Map<String, Double> weights;
private final int hashCode;

public WeightedRouting() {
this.attributeName = "";
this.weights = new HashMap<>(3);
this("", new HashMap<>(3));
}

public WeightedRouting(String attributeName, Map<String, Double> weights) {
this.attributeName = attributeName;
this.weights = weights;
this.weights = Collections.unmodifiableMap(weights);
this.hashCode = Objects.hash(this.attributeName, this.weights);
}

public WeightedRouting(WeightedRouting weightedRouting) {
this.attributeName = weightedRouting.attributeName();
this.weights = weightedRouting.weights;
this(weightedRouting.attributeName(), weightedRouting.weights);
}

public WeightedRouting(StreamInput in) throws IOException {
attributeName = in.readString();
weights = (Map<String, Double>) in.readGenericValue();
this(in.readString(), (Map<String, Double>) in.readGenericValue());
}

public boolean isSet() {
Expand All @@ -70,7 +70,7 @@ public boolean equals(Object o) {

@Override
public int hashCode() {
return Objects.hash(attributeName, weights);
return hashCode;
}

@Override
Expand Down

0 comments on commit 8d9e12d

Please sign in to comment.