Add QName.hashCode() cache 37/40337/6
authorRobert Varga <rovarga@cisco.com>
Tue, 14 Jun 2016 23:40:39 +0000 (01:40 +0200)
committerTony Tkacik <ttkacik@cisco.com>
Tue, 21 Jun 2016 11:46:28 +0000 (11:46 +0000)
QName is usually involved in hash-based lookups, hence it is
useful to reuse a computed hash code so that constants do not
spend cycles on computing it more than once.

Add a field which will be lazily initiated to contain the result
of hashCode(). This has no impact on memory footprint.

Change-Id: I8a0b89599ed1029e2c572535826c52b4b837e265
Signed-off-by: Robert Varga <rovarga@cisco.com>
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/QName.java

index 97a9aaab1ae16d167c0f532572c298b8af65c86d..06dc6e605daec62ab78d03fcf3505bcacc08dd8c 100644 (file)
@@ -61,10 +61,11 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
     private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
     private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
 
-    // Mandatory
+    // Non-null
     private final QNameModule module;
-    // Mandatory
+    // Non-null
     private final String localName;
+    private transient int hash;
 
     private QName(final QNameModule module, final String localName) {
         this.localName = checkLocalName(localName);
@@ -177,11 +178,10 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
 
     @Override
     public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + Objects.hashCode(localName);
-        result = prime * result + module.hashCode();
-        return result;
+        if (hash == 0) {
+            hash = Objects.hash(module, localName);
+        }
+        return hash;
     }
 
     /**