Use byte[].clone() 22/70622/6
authorRobert Varga <robert.varga@pantheon.tech>
Sat, 7 Apr 2018 12:05:27 +0000 (14:05 +0200)
committerClaudio David Gasparini <claudio.gasparini@pantheon.tech>
Thu, 26 Apr 2018 09:15:01 +0000 (09:15 +0000)
BGPDocumentedException can be made more efficient by using
byte[].clone() instead of Arrays.copyOf(). Also pre-cache empty
data and return it when needed.

Change-Id: Ib4e36522f0d3a734621349c1b62865496d330009
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPDocumentedException.java

index d262d3fa7e2f111890760448a63f93ad9e97a17c..a543e0f4c8a937c4248f8fd2fb04258da66391e9 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.protocol.bgp.parser;
 
 import com.google.common.base.Preconditions;
 import com.google.common.primitives.UnsignedBytes;
-import java.util.Arrays;
 import org.opendaylight.protocol.util.Values;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -24,6 +23,8 @@ public final class BGPDocumentedException extends Exception {
 
     private static final Logger LOG = LoggerFactory.getLogger(BGPDocumentedException.class);
 
+    private static final byte[] EMPTY = new byte[0];
+
     private final BGPError error;
 
     private final byte[] data;
@@ -81,7 +82,7 @@ public final class BGPDocumentedException extends Exception {
             final Exception cause) {
         super(message, cause);
         this.error = error;
-        this.data = data == null ? null : Arrays.copyOf(data, data.length);
+        this.data = data == null || data.length == 0 ? null : data.clone();
         LOG.error("Error = {}", error, this);
     }
 
@@ -91,7 +92,7 @@ public final class BGPDocumentedException extends Exception {
      * @return documented error
      */
     public BGPError getError() {
-        return this.error;
+        return error;
     }
 
     /**
@@ -100,7 +101,7 @@ public final class BGPDocumentedException extends Exception {
      * @return byte array data
      */
     public byte[] getData() {
-        return (this.data != null) ? Arrays.copyOf(this.data, this.data.length) : new byte[0];
+        return data != null ? data.clone() : EMPTY;
     }
 
     public static BGPDocumentedException badMessageLength(final String message, final int length) {
@@ -109,6 +110,5 @@ public final class BGPDocumentedException extends Exception {
         return new BGPDocumentedException(message, BGPError.BAD_MSG_LENGTH, new byte[] {
             UnsignedBytes.checkedCast(length / (Values.UNSIGNED_BYTE_MAX_VALUE + 1)),
             UnsignedBytes.checkedCast(length % (Values.UNSIGNED_BYTE_MAX_VALUE + 1)) });
-
     }
 }