Skip to content

Commit ea3f506

Browse files
core: avoid allocating Iterators in EquivalentAddressGroup, which is called for each new RPC
Benchmarked with 3 runs of 4 forks Before: Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 255593 156248.670 ± 563.514 ns/op Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 261443 152753.415 ± 500.957 ns/op Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 258978 154205.374 ± 453.808 ns/op After: Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 262194 152313.101 ± 502.563 ns/op Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 264811 150809.474 ± 477.459 ns/op Benchmark (direct) (transport) Mode Cnt Score Error Units TransportBenchmark.unaryCall1024 true NETTY sample 263606 151501.729 ± 593.149 ns/op
1 parent c4f7f5c commit ea3f506

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

core/src/main/java/io/grpc/EquivalentAddressGroup.java

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,26 @@ public final class EquivalentAddressGroup {
5050

5151
private final List<SocketAddress> addrs;
5252

53+
/**
54+
* {@link SocketAddress} docs say that the addresses are immutable, so we cache the hashCode.
55+
*/
56+
private final int hashCode;
57+
58+
/**
59+
* List constructor.
60+
*/
5361
public EquivalentAddressGroup(List<SocketAddress> addrs) {
5462
Preconditions.checkArgument(!addrs.isEmpty(), "addrs is empty");
5563
this.addrs = Collections.unmodifiableList(new ArrayList<SocketAddress>(addrs));
64+
hashCode = this.addrs.hashCode();
5665
}
5766

67+
/**
68+
* Singleton constructor.
69+
*/
5870
public EquivalentAddressGroup(SocketAddress addr) {
5971
this.addrs = Collections.singletonList(addr);
72+
hashCode = addrs.hashCode();
6073
}
6174

6275
/**
@@ -73,14 +86,25 @@ public String toString() {
7386

7487
@Override
7588
public int hashCode() {
76-
return addrs.hashCode();
89+
// Avoids creating an iterator on the underlying array list.
90+
return hashCode;
7791
}
7892

7993
@Override
8094
public boolean equals(Object other) {
8195
if (!(other instanceof EquivalentAddressGroup)) {
8296
return false;
8397
}
84-
return addrs.equals(((EquivalentAddressGroup) other).addrs);
98+
EquivalentAddressGroup that = (EquivalentAddressGroup) other;
99+
if (addrs.size() != that.addrs.size()) {
100+
return false;
101+
}
102+
// Avoids creating an iterator on the underlying array list.
103+
for (int i = 0; i < addrs.size(); i++) {
104+
if (!addrs.get(i).equals(that.addrs.get(i))) {
105+
return false;
106+
}
107+
}
108+
return true;
85109
}
86110
}

0 commit comments

Comments
 (0)