Browse Source

Exploit DiscoveryNode immutability in toString

DiscoveryNode is immutable yet we rebuild DiscoveryNode#toString on
every invocation. Most importantly, this just leads to unnecessary
allocations. This is most germane to ZenDiscovery and the processing of
cluster states where DiscoveryNode#toString is invoked when submitting
update tasks and processing cluster state updates.

Closes #17543
Jason Tedor 9 years ago
parent
commit
e76038e076
1 changed files with 21 additions and 16 deletions
  1. 21 16
      core/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java

+ 21 - 16
core/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java

@@ -312,25 +312,30 @@ public class DiscoveryNode implements Writeable<DiscoveryNode>, ToXContent {
         return nodeId.hashCode();
     }
 
+    private String toString;
+
     @Override
     public String toString() {
-        StringBuilder sb = new StringBuilder();
-        if (nodeName.length() > 0) {
-            sb.append('{').append(nodeName).append('}');
-        }
-        if (nodeId != null) {
-            sb.append('{').append(nodeId).append('}');
-        }
-        if (Strings.hasLength(hostName)) {
-            sb.append('{').append(hostName).append('}');
-        }
-        if (address != null) {
-            sb.append('{').append(address).append('}');
-        }
-        if (!attributes.isEmpty()) {
-            sb.append(attributes);
+        if (toString == null) {
+            StringBuilder sb = new StringBuilder();
+            if (nodeName.length() > 0) {
+                sb.append('{').append(nodeName).append('}');
+            }
+            if (nodeId != null) {
+                sb.append('{').append(nodeId).append('}');
+            }
+            if (Strings.hasLength(hostName)) {
+                sb.append('{').append(hostName).append('}');
+            }
+            if (address != null) {
+                sb.append('{').append(address).append('}');
+            }
+            if (!attributes.isEmpty()) {
+                sb.append(attributes);
+            }
+            toString = sb.toString();
         }
-        return sb.toString();
+        return toString;
     }
 
     @Override