ByteArray: do not instantiate arrays if not needed 42/35942/2
authorRobert Varga <rovarga@cisco.com>
Wed, 24 Feb 2016 19:41:03 +0000 (20:41 +0100)
committerMilos Fabian <milfabia@cisco.com>
Tue, 8 Mar 2016 22:09:04 +0000 (22:09 +0000)
Move array instantiation into the block where it is used, skipping it
completely in the case we have properly-sized array.

Change-Id: Ie5027f429830a39bfd2835cc5751cb3d6c27dd1e
Signed-off-by: Robert Varga <rovarga@cisco.com>
(cherry picked from commit 439698fb6b677d9c3e121a0031499b4c68b59c20)

util/src/main/java/org/opendaylight/protocol/util/ByteArray.java

index 93fbb278aeb117f178eac3fb1834a32dcd0ed57e..10f7f2424130e355ad36e7b4f064a4747390a720 100644 (file)
@@ -118,14 +118,14 @@ public final class ByteArray {
      */
     public static int bytesToInt(final byte[] bytes) {
         Preconditions.checkArgument(bytes.length <= Integer.SIZE / Byte.SIZE, "Cannot convert bytes to integer. Byte array too big.");
-        byte[] res = new byte[Integer.SIZE / Byte.SIZE];
+        final byte[] res;
         if (bytes.length != Integer.SIZE / Byte.SIZE) {
+            res = new byte[Integer.SIZE / Byte.SIZE];
             System.arraycopy(bytes, 0, res, Integer.SIZE / Byte.SIZE - bytes.length, bytes.length);
         } else {
             res = bytes;
         }
-        final ByteBuffer buff = ByteBuffer.wrap(res);
-        return buff.getInt();
+        return ByteBuffer.wrap(res).getInt();
     }
 
     /**
@@ -137,14 +137,14 @@ public final class ByteArray {
      */
     public static long bytesToLong(final byte[] bytes) {
         Preconditions.checkArgument(bytes.length <= Long.SIZE / Byte.SIZE, "Cannot convert bytes to long.Byte array too big.");
-        byte[] res = new byte[Long.SIZE / Byte.SIZE];
+        final byte[] res;
         if (bytes.length != Long.SIZE / Byte.SIZE) {
+            res = new byte[Long.SIZE / Byte.SIZE];
             System.arraycopy(bytes, 0, res, Long.SIZE / Byte.SIZE - bytes.length, bytes.length);
         } else {
             res = bytes;
         }
-        final ByteBuffer buff = ByteBuffer.wrap(res);
-        return buff.getLong();
+        return ByteBuffer.wrap(res).getLong();
     }
 
     /**